docu
[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 }
679
680 /**
681  * Test if we're connected to the given peer.
682  *
683  * @param n neighbour entry of peer to test
684  * @return GNUNET_YES if we are connected, GNUNET_NO if not
685  */
686 static int
687 test_connected (struct NeighbourMapEntry *n)
688 {
689   if (NULL == n)
690     return GNUNET_NO;
691   switch (n->state)
692   {
693   case S_NOT_CONNECTED:
694   case S_INIT_ATS:
695   case S_INIT_BLACKLIST:
696   case S_CONNECT_SENT:
697   case S_CONNECT_RECV_BLACKLIST_INBOUND:
698   case S_CONNECT_RECV_ATS:
699   case S_CONNECT_RECV_BLACKLIST:
700   case S_CONNECT_RECV_ACK:
701     return GNUNET_NO;
702   case S_CONNECTED:
703   case S_RECONNECT_ATS:
704   case S_RECONNECT_BLACKLIST:
705   case S_RECONNECT_SENT:
706   case S_CONNECTED_SWITCHING_BLACKLIST:
707   case S_CONNECTED_SWITCHING_CONNECT_SENT:
708     return GNUNET_YES;
709   case S_DISCONNECT:
710   case S_DISCONNECT_FINISHED:
711     return GNUNET_NO;
712   default:
713     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
714     GNUNET_break (0);
715     break;
716   }
717   return GNUNET_SYSERR;
718 }
719
720 /**
721  * Send information about a new outbound quota to our clients.
722  *
723  * @param target affected peer
724  * @param quota new quota
725  */
726 static void
727 send_outbound_quota (const struct GNUNET_PeerIdentity *target,
728                      struct GNUNET_BANDWIDTH_Value32NBO quota)
729 {
730   struct QuotaSetMessage q_msg;
731
732   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
733               "Sending outbound quota of %u Bps for peer `%s' to all clients\n",
734               ntohl (quota.value__), GNUNET_i2s (target));
735   q_msg.header.size = htons (sizeof (struct QuotaSetMessage));
736   q_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA);
737   q_msg.quota = quota;
738   q_msg.peer = (*target);
739   GST_clients_broadcast (&q_msg.header, GNUNET_NO);
740 }
741
742
743 /**
744  * We don't need a given neighbour address any more.
745  * Release its resources and give appropriate notifications
746  * to ATS and other subsystems.
747  *
748  * @param na address we are done with; 'na' itself must NOT be 'free'd, only the contents!
749  */
750 static void
751 free_address (struct NeighbourAddress *na)
752 {
753   if (GNUNET_YES == na->ats_active)
754   {
755     GST_validation_set_address_use (na->address, na->session, GNUNET_NO, __LINE__);
756     GNUNET_ATS_address_in_use (GST_ats, na->address, na->session, GNUNET_NO);
757   }
758
759   na->ats_active = GNUNET_NO;
760   if (NULL != na->address)
761   {
762     GNUNET_HELLO_address_free (na->address);
763     na->address = NULL;
764   }
765   na->session = NULL;
766 }
767
768
769 /**
770  * Initialize the 'struct NeighbourAddress'.
771  *
772  * @param na neighbour address to initialize
773  * @param address address of the other peer, NULL if other peer
774  *                       connected to us
775  * @param session session to use (or NULL, in which case an
776  *        address must be setup)
777  * @param bandwidth_in inbound quota to be used when connection is up
778  * @param bandwidth_out outbound quota to be used when connection is up
779  * @param is_active GNUNET_YES to mark this as the active address with ATS
780  */
781 static void
782 set_address (struct NeighbourAddress *na,
783              const struct GNUNET_HELLO_Address *address,
784              struct Session *session,
785              struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
786              struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
787              int is_active)
788 {
789   struct GNUNET_TRANSPORT_PluginFunctions *papi;
790
791   if (NULL == (papi = GST_plugins_find (address->transport_name)))  
792   {
793     GNUNET_break (0);
794     return;
795   }
796   if (session == na->session)
797   {
798     na->bandwidth_in = bandwidth_in;
799     na->bandwidth_out = bandwidth_out;
800     if (is_active != na->ats_active)
801     {
802       na->ats_active = is_active;
803       GNUNET_ATS_address_in_use (GST_ats, na->address, na->session, is_active);
804       GST_validation_set_address_use (na->address, na->session, is_active,  __LINE__);
805     }
806     if (GNUNET_YES == is_active)
807     {
808       /* FIXME: is this the right place to set quotas? */
809       GST_neighbours_set_incoming_quota (&address->peer, bandwidth_in);
810       send_outbound_quota (&address->peer, bandwidth_out);
811     }    
812     return;
813   }
814   free_address (na);
815   if (NULL == session)
816     session = papi->get_session (papi->cls, address);    
817   if (NULL == session)
818   {
819     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
820                 "Failed to obtain new session for peer `%s' and  address '%s'\n",
821                 GNUNET_i2s (&address->peer), GST_plugins_a2s (address));    
822     GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
823     return;
824   }
825   na->address = GNUNET_HELLO_address_copy (address);
826   na->bandwidth_in = bandwidth_in;
827   na->bandwidth_out = bandwidth_out;
828   na->session = session;
829   na->ats_active = is_active;
830   if (GNUNET_YES == is_active)
831   {
832     /* Telling ATS about new session */
833     GNUNET_ATS_address_in_use (GST_ats, na->address, na->session, GNUNET_YES);
834     GST_validation_set_address_use (na->address, na->session, GNUNET_YES,  __LINE__);
835
836     /* FIXME: is this the right place to set quotas? */
837     GST_neighbours_set_incoming_quota (&address->peer, bandwidth_in);
838     send_outbound_quota (&address->peer, bandwidth_out);
839   }
840 }
841
842
843 /**
844  * Free a neighbour map entry.
845  *
846  * @param n entry to free
847  * @param keep_sessions GNUNET_NO to tell plugin to terminate sessions,
848  *                      GNUNET_YES to keep all sessions
849  */
850 static void
851 free_neighbour (struct NeighbourMapEntry *n, int keep_sessions)
852 {
853   struct MessageQueue *mq;
854   struct GNUNET_TRANSPORT_PluginFunctions *papi;
855   struct GNUNET_HELLO_Address *backup_primary;
856
857   n->is_active = NULL; /* always free'd by its own continuation! */
858
859   /* fail messages currently in the queue */
860   while (NULL != (mq = n->messages_head))
861   {
862     GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
863     if (NULL != mq->cont)
864       mq->cont (mq->cont_cls, GNUNET_SYSERR, mq->message_buf_size, 0);
865     GNUNET_free (mq);
866   }
867   /* It is too late to send other peer disconnect notifications, but at
868      least internally we need to get clean... */
869   if (GNUNET_YES == test_connected (n))
870   {
871     GNUNET_STATISTICS_set (GST_stats, 
872                            gettext_noop ("# peers connected"), 
873                            --neighbours_connected,
874                            GNUNET_NO);
875     disconnect_notify_cb (callback_cls, &n->id);
876   }
877
878   n->state = S_DISCONNECT_FINISHED;
879
880   if (NULL != n->primary_address.address)
881     backup_primary = GNUNET_HELLO_address_copy(n->primary_address.address);
882   else
883     backup_primary = NULL;
884
885   /* free addresses and mark as unused */
886   free_address (&n->primary_address);
887   free_address (&n->alternative_address);
888
889   /* FIXME-PLUGIN-API: This does not seem to guarantee that all
890      transport sessions eventually get killed due to inactivity; they
891      MUST have their own timeout logic (but at least TCP doesn't have
892      one yet).  Are we sure that EVERY 'session' of a plugin is
893      actually cleaned up this way!?  Note that if we are switching
894      between two TCP sessions to the same peer, the existing plugin
895      API gives us not even the means to selectively kill only one of
896      them! Killing all sessions like this seems to be very, very
897      wrong. */
898
899   /* cut transport-level connection */
900   if ((GNUNET_NO == keep_sessions) &&
901       (NULL != backup_primary) &&
902       (NULL != (papi = GST_plugins_find (backup_primary->transport_name))))
903     papi->disconnect (papi->cls, &n->id);
904
905   GNUNET_free_non_null (backup_primary);
906
907   GNUNET_assert (GNUNET_YES ==
908                  GNUNET_CONTAINER_multihashmap_remove (neighbours,
909                                                        &n->id.hashPubKey, n));
910
911   // FIXME-ATS-API: we might want to be more specific about
912   // which states we do this from in the future (ATS should
913   // have given us a 'suggest_address' handle, and if we have
914   // such a handle, we should cancel the operation here!
915   GNUNET_ATS_suggest_address_cancel (GST_ats, &n->id);
916
917   if (GNUNET_SCHEDULER_NO_TASK != n->task)
918   {
919     GNUNET_SCHEDULER_cancel (n->task);
920     n->task = GNUNET_SCHEDULER_NO_TASK;
921   }
922   /* free rest of memory */
923   GNUNET_free (n);
924 }
925
926 /**
927  * Transmit a message using the current session of the given
928  * neighbour.
929  *
930  * @param n entry for the recipient
931  * @param msgbuf buffer to transmit
932  * @param msgbuf_size number of bytes in buffer
933  * @param priority transmission priority
934  * @param timeout transmission timeout
935  * @param cont continuation to call when finished (can be NULL)
936  * @param cont_cls closure for cont
937  */
938 static void
939 send_with_session (struct NeighbourMapEntry *n,
940                    const char *msgbuf, size_t msgbuf_size,
941                    uint32_t priority,
942                    struct GNUNET_TIME_Relative timeout,
943                    GNUNET_TRANSPORT_TransmitContinuation cont,
944                    void *cont_cls)
945 {
946   struct GNUNET_TRANSPORT_PluginFunctions *papi;
947
948   GNUNET_assert (n->primary_address.session != NULL);
949   if ( ((NULL == (papi = GST_plugins_find (n->primary_address.address->transport_name)) ||
950          (-1 == papi->send (papi->cls,
951                             n->primary_address.session,
952                             msgbuf, msgbuf_size,
953                             priority,
954                             timeout,
955                             cont, cont_cls)))) &&
956        (NULL != cont))
957     cont (cont_cls, &n->id, GNUNET_SYSERR, msgbuf_size, 0);
958   GNUNET_break (NULL != papi);
959 }
960
961
962 /**
963  * Master task run for every neighbour.  Performs all of the time-related
964  * activities (keep alive, send next message, disconnect if idle, finish
965  * clean up after disconnect).
966  *
967  * @param cls the 'struct NeighbourMapEntry' for which we are running
968  * @param tc scheduler context (unused)
969  */
970 static void
971 master_task (void *cls,
972              const struct GNUNET_SCHEDULER_TaskContext *tc);
973
974
975 /**
976  * Function called when the 'DISCONNECT' message has been sent by the
977  * plugin.  Frees the neighbour --- if the entry still exists.
978  *
979  * @param cls NULL
980  * @param target identity of the neighbour that was disconnected
981  * @param result GNUNET_OK if the disconnect got out successfully
982  * @param payload bytes payload
983  * @param physical bytes physical
984  */
985 static void
986 send_disconnect_cont (void *cls, const struct GNUNET_PeerIdentity *target,
987                       int result, size_t payload, size_t physical)
988 {
989   struct NeighbourMapEntry *n;
990
991   n = lookup_neighbour (target);
992   if (NULL == n)
993     return; /* already gone */
994   if (S_DISCONNECT != n->state)
995     return; /* have created a fresh entry since */
996   n->state = S_DISCONNECT;
997   if (GNUNET_SCHEDULER_NO_TASK != n->task)
998     GNUNET_SCHEDULER_cancel (n->task);
999   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
1000 }
1001
1002
1003 /**
1004  * Transmit a DISCONNECT message to the other peer.
1005  *
1006  * @param n neighbour to send DISCONNECT message.
1007  */
1008 static void
1009 send_disconnect (struct NeighbourMapEntry *n)
1010 {
1011   struct SessionDisconnectMessage disconnect_msg;
1012
1013   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1014               "Sending DISCONNECT message to peer `%4s'\n",
1015               GNUNET_i2s (&n->id));
1016   disconnect_msg.header.size = htons (sizeof (struct SessionDisconnectMessage));
1017   disconnect_msg.header.type =
1018       htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT);
1019   disconnect_msg.reserved = htonl (0);
1020   disconnect_msg.purpose.size =
1021       htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
1022              sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
1023              sizeof (struct GNUNET_TIME_AbsoluteNBO));
1024   disconnect_msg.purpose.purpose =
1025       htonl (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT);
1026   disconnect_msg.timestamp =
1027       GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1028   disconnect_msg.public_key = GST_my_public_key;
1029   GNUNET_assert (GNUNET_OK ==
1030                  GNUNET_CRYPTO_rsa_sign (GST_my_private_key,
1031                                          &disconnect_msg.purpose,
1032                                          &disconnect_msg.signature));
1033
1034   send_with_session (n,
1035                      (const char *) &disconnect_msg, sizeof (disconnect_msg),
1036                      UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_REL,
1037                      &send_disconnect_cont, NULL);
1038   GNUNET_STATISTICS_update (GST_stats,
1039                             gettext_noop
1040                             ("# DISCONNECT messages sent"), 1,
1041                             GNUNET_NO);
1042 }
1043
1044
1045 /**
1046  * Disconnect from the given neighbour, clean up the record.
1047  *
1048  * @param n neighbour to disconnect from
1049  */
1050 static void
1051 disconnect_neighbour (struct NeighbourMapEntry *n)
1052 {
1053   /* depending on state, notify neighbour and/or upper layers of this peer 
1054      about disconnect */
1055   switch (n->state)
1056   {
1057   case S_NOT_CONNECTED:
1058   case S_INIT_ATS:
1059   case S_INIT_BLACKLIST:
1060     /* other peer is completely unaware of us, no need to send DISCONNECT */
1061     n->state = S_DISCONNECT_FINISHED;
1062     free_neighbour (n, GNUNET_NO);
1063     return;
1064   case S_CONNECT_SENT:
1065     send_disconnect (n); 
1066     n->state = S_DISCONNECT;
1067     break;
1068   case S_CONNECT_RECV_BLACKLIST_INBOUND:
1069   case S_CONNECT_RECV_ATS:
1070   case S_CONNECT_RECV_BLACKLIST:
1071     /* we never ACK'ed the other peer's request, no need to send DISCONNECT */
1072     n->state = S_DISCONNECT_FINISHED;
1073     free_neighbour (n, GNUNET_NO);
1074     return;
1075   case S_CONNECT_RECV_ACK:
1076     /* we DID ACK the other peer's request, must send DISCONNECT */
1077     send_disconnect (n); 
1078     n->state = S_DISCONNECT;
1079     break;   
1080   case S_CONNECTED:
1081   case S_RECONNECT_BLACKLIST:
1082   case S_RECONNECT_SENT:
1083   case S_CONNECTED_SWITCHING_BLACKLIST:
1084   case S_CONNECTED_SWITCHING_CONNECT_SENT:
1085     /* we are currently connected, need to send disconnect and do
1086        internal notifications and update statistics */
1087     send_disconnect (n);
1088     GNUNET_STATISTICS_set (GST_stats, 
1089                            gettext_noop ("# peers connected"), 
1090                            --neighbours_connected,
1091                            GNUNET_NO);
1092     disconnect_notify_cb (callback_cls, &n->id);
1093     n->state = S_DISCONNECT;
1094     break;
1095   case S_RECONNECT_ATS:
1096     /* ATS address request timeout, disconnect without sending disconnect message */
1097     GNUNET_STATISTICS_set (GST_stats,
1098                            gettext_noop ("# peers connected"),
1099                            --neighbours_connected,
1100                            GNUNET_NO);
1101     disconnect_notify_cb (callback_cls, &n->id);
1102     n->state = S_DISCONNECT;
1103     break;
1104   case S_DISCONNECT:
1105     /* already disconnected, ignore */
1106     break;
1107   case S_DISCONNECT_FINISHED:
1108     /* already cleaned up, how did we get here!? */
1109     GNUNET_assert (0);
1110     break;
1111   default:
1112     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
1113     GNUNET_break (0);
1114     break;
1115   }
1116   /* schedule timeout to clean up */
1117   if (GNUNET_SCHEDULER_NO_TASK != n->task)
1118     GNUNET_SCHEDULER_cancel (n->task);
1119   n->task = GNUNET_SCHEDULER_add_delayed (DISCONNECT_SENT_TIMEOUT,
1120                                           &master_task, n);
1121 }
1122
1123
1124 /**
1125  * We're done with our transmission attempt, continue processing.
1126  *
1127  * @param cls the 'struct MessageQueue' of the message
1128  * @param receiver intended receiver
1129  * @param success whether it worked or not
1130  * @param size_payload bytes payload sent
1131  * @param physical bytes sent on wire
1132  */
1133 static void
1134 transmit_send_continuation (void *cls,
1135                             const struct GNUNET_PeerIdentity *receiver,
1136                             int success, size_t size_payload, size_t physical)
1137 {
1138   struct MessageQueue *mq = cls;
1139   struct NeighbourMapEntry *n;
1140
1141   if (NULL == (n = lookup_neighbour (receiver)))
1142   {
1143     GNUNET_free (mq);
1144     return; /* disconnect or other error while transmitting, can happen */
1145   }
1146   if (n->is_active == mq)
1147   {
1148     /* this is still "our" neighbour, remove us from its queue
1149        and allow it to send the next message now */
1150     n->is_active = NULL;
1151     if (GNUNET_SCHEDULER_NO_TASK != n->task)
1152       GNUNET_SCHEDULER_cancel (n->task);
1153     n->task = GNUNET_SCHEDULER_add_now (&master_task, n);    
1154   }
1155   if (bytes_in_send_queue < mq->message_buf_size)
1156   {
1157       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1158                   "Bytes_in_send_queue `%u', Message_size %u, result: %s, payload %u, on wire %u\n",
1159                   bytes_in_send_queue, mq->message_buf_size,
1160                   (GNUNET_OK == success) ? "OK" : "FAIL",
1161                   size_payload, physical);
1162       GNUNET_break (0);
1163   }
1164
1165
1166   GNUNET_break (size_payload == mq->message_buf_size);
1167   bytes_in_send_queue -= mq->message_buf_size;
1168   GNUNET_STATISTICS_set (GST_stats,
1169                         gettext_noop
1170                          ("# bytes in message queue for other peers"),
1171                          bytes_in_send_queue, GNUNET_NO);
1172   if (GNUNET_OK == success)
1173     GNUNET_STATISTICS_update (GST_stats,
1174                               gettext_noop
1175                               ("# messages transmitted to other peers"),
1176                               1, GNUNET_NO);
1177   else
1178     GNUNET_STATISTICS_update (GST_stats,
1179                               gettext_noop
1180                               ("# transmission failures for messages to other peers"),
1181                               1, GNUNET_NO);
1182   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1183               "Sending message to `%s' of type %u was a %s\n",
1184               GNUNET_i2s (receiver),
1185               ntohs (((struct GNUNET_MessageHeader *) mq->message_buf)->type),
1186               (success == GNUNET_OK) ? "success" : "FAILURE");
1187   if (NULL != mq->cont)
1188     mq->cont (mq->cont_cls, success, size_payload, physical);
1189   GNUNET_free (mq);
1190 }
1191
1192
1193 /**
1194  * Check the message list for the given neighbour and if we can
1195  * send a message, do so.  This function should only be called
1196  * if the connection is at least generally ready for transmission.
1197  * While we will only send one message at a time, no bandwidth
1198  * quota management is performed here.  If a message was given to
1199  * the plugin, the continuation will automatically re-schedule
1200  * the 'master' task once the next message might be transmitted.
1201  *
1202  * @param n target peer for which to transmit
1203  */
1204 static void
1205 try_transmission_to_peer (struct NeighbourMapEntry *n)
1206 {
1207   struct MessageQueue *mq;
1208   struct GNUNET_TIME_Relative timeout;
1209
1210   if (NULL == n->primary_address.address)
1211   {
1212     /* no address, why are we here? */
1213     GNUNET_break (0);
1214     return;
1215   }
1216   if ((0 == n->primary_address.address->address_length) && 
1217       (NULL == n->primary_address.session))
1218   {
1219     /* no address, why are we here? */
1220     GNUNET_break (0);
1221     return;
1222   }
1223   if (NULL != n->is_active)
1224   {
1225     /* transmission already pending */
1226     return;                     
1227   }
1228
1229   /* timeout messages from the queue that are past their due date */
1230   while (NULL != (mq = n->messages_head))
1231   {
1232     timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1233     if (timeout.rel_value > 0)
1234       break;
1235     GNUNET_STATISTICS_update (GST_stats,
1236                               gettext_noop
1237                               ("# messages timed out while in transport queue"),
1238                               1, GNUNET_NO);
1239     GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
1240     n->is_active = mq;
1241     transmit_send_continuation (mq, &n->id, GNUNET_SYSERR, mq->message_buf_size, 0);     /* timeout */
1242   }
1243   if (NULL == mq)
1244     return;                     /* no more messages */
1245   GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
1246   n->is_active = mq;
1247   send_with_session (n,
1248                      mq->message_buf, mq->message_buf_size,
1249                      0 /* priority */, timeout,
1250                      &transmit_send_continuation, mq);
1251 }
1252
1253
1254 /**
1255  * Send keepalive message to the neighbour.  Must only be called
1256  * if we are on 'connected' state or while trying to switch addresses.
1257  * Will internally determine if a keepalive is truly needed (so can
1258  * always be called).
1259  *
1260  * @param n neighbour that went idle and needs a keepalive
1261  */
1262 static void
1263 send_keepalive (struct NeighbourMapEntry *n)
1264 {
1265   struct GNUNET_MessageHeader m;
1266
1267   GNUNET_assert ((S_CONNECTED == n->state) ||
1268                  (S_CONNECTED_SWITCHING_BLACKLIST == n->state) ||
1269                  (S_CONNECTED_SWITCHING_CONNECT_SENT));
1270   if (GNUNET_TIME_absolute_get_remaining (n->keep_alive_time).rel_value > 0)
1271     return; /* no keepalive needed at this time */
1272   m.size = htons (sizeof (struct GNUNET_MessageHeader));
1273   m.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE);
1274   send_with_session (n,
1275                      (const void *) &m, sizeof (m),
1276                      UINT32_MAX /* priority */,
1277                      KEEPALIVE_FREQUENCY,
1278                      NULL, NULL);
1279   GNUNET_STATISTICS_update (GST_stats, gettext_noop ("# keepalives sent"), 1,
1280                             GNUNET_NO);
1281   n->expect_latency_response = GNUNET_YES;
1282   n->last_keep_alive_time = GNUNET_TIME_absolute_get ();
1283   n->keep_alive_time = GNUNET_TIME_relative_to_absolute (KEEPALIVE_FREQUENCY);
1284 }
1285
1286
1287 /**
1288  * Keep the connection to the given neighbour alive longer,
1289  * we received a KEEPALIVE (or equivalent); send a response.
1290  *
1291  * @param neighbour neighbour to keep alive (by sending keep alive response)
1292  */
1293 void
1294 GST_neighbours_keepalive (const struct GNUNET_PeerIdentity *neighbour)
1295 {
1296   struct NeighbourMapEntry *n;
1297   struct GNUNET_MessageHeader m;
1298
1299   if (NULL == (n = lookup_neighbour (neighbour)))
1300   {
1301     GNUNET_STATISTICS_update (GST_stats,
1302                               gettext_noop
1303                               ("# KEEPALIVE messages discarded (peer unknown)"),
1304                               1, GNUNET_NO);
1305     return;
1306   }
1307   if (NULL == n->primary_address.session)
1308   {
1309     GNUNET_STATISTICS_update (GST_stats,
1310                               gettext_noop
1311                               ("# KEEPALIVE messages discarded (no session)"),
1312                               1, GNUNET_NO);
1313     return;
1314   }
1315   /* send reply to allow neighbour to measure latency */
1316   m.size = htons (sizeof (struct GNUNET_MessageHeader));
1317   m.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE_RESPONSE);
1318   send_with_session(n,
1319                     (const void *) &m, sizeof (m),
1320                     UINT32_MAX /* priority */,
1321                     KEEPALIVE_FREQUENCY,
1322                     NULL, NULL);
1323 }
1324
1325
1326 /**
1327  * We received a KEEP_ALIVE_RESPONSE message and use this to calculate
1328  * latency to this peer.  Pass the updated information (existing ats
1329  * plus calculated latency) to ATS.
1330  *
1331  * @param neighbour neighbour to keep alive
1332  * @param ats performance data
1333  * @param ats_count number of entries in ats
1334  */
1335 void
1336 GST_neighbours_keepalive_response (const struct GNUNET_PeerIdentity *neighbour,
1337                                    const struct GNUNET_ATS_Information *ats,
1338                                    uint32_t ats_count)
1339 {
1340   struct NeighbourMapEntry *n;
1341   uint32_t latency;
1342   struct GNUNET_ATS_Information ats_new[ats_count + 1];
1343
1344   if (NULL == (n = lookup_neighbour (neighbour)))
1345   {
1346     GNUNET_STATISTICS_update (GST_stats,
1347                               gettext_noop
1348                               ("# KEEPALIVE_RESPONSE messages discarded (not connected)"),
1349                               1, GNUNET_NO);
1350     return;
1351   }
1352   if ( (S_CONNECTED != n->state) ||
1353        (GNUNET_YES != n->expect_latency_response) )
1354   {
1355     GNUNET_STATISTICS_update (GST_stats,
1356                               gettext_noop
1357                               ("# KEEPALIVE_RESPONSE messages discarded (not expected)"),
1358                               1, GNUNET_NO);
1359     return;
1360   }
1361   n->expect_latency_response = GNUNET_NO;
1362   n->latency = GNUNET_TIME_absolute_get_duration (n->last_keep_alive_time);
1363   n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1364   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1365               "Latency for peer `%s' is %llu ms\n",
1366               GNUNET_i2s (&n->id), n->latency.rel_value);
1367   memcpy (ats_new, ats, sizeof (struct GNUNET_ATS_Information) * ats_count);
1368   /* append latency */
1369   ats_new[ats_count].type = htonl (GNUNET_ATS_QUALITY_NET_DELAY);
1370   if (n->latency.rel_value > UINT32_MAX)
1371     latency = UINT32_MAX;
1372   else
1373     latency = n->latency.rel_value;
1374   ats_new[ats_count].value = htonl (latency);
1375   GNUNET_ATS_address_update (GST_ats, 
1376                              n->primary_address.address, 
1377                              n->primary_address.session, ats_new,
1378                              ats_count + 1);
1379 }
1380
1381
1382 /**
1383  * We have received a message from the given sender.  How long should
1384  * we delay before receiving more?  (Also used to keep the peer marked
1385  * as live).
1386  *
1387  * @param sender sender of the message
1388  * @param size size of the message
1389  * @param do_forward set to GNUNET_YES if the message should be forwarded to clients
1390  *                   GNUNET_NO if the neighbour is not connected or violates the quota,
1391  *                   GNUNET_SYSERR if the connection is not fully up yet
1392  * @return how long to wait before reading more from this sender
1393  */
1394 struct GNUNET_TIME_Relative
1395 GST_neighbours_calculate_receive_delay (const struct GNUNET_PeerIdentity
1396                                         *sender, ssize_t size, int *do_forward)
1397 {
1398   struct NeighbourMapEntry *n;
1399   struct GNUNET_TIME_Relative ret;
1400   
1401   if (NULL == neighbours)
1402   {
1403     *do_forward = GNUNET_NO;
1404     return GNUNET_TIME_UNIT_FOREVER_REL; /* This can happen during shutdown */
1405   }
1406   if (NULL == (n = lookup_neighbour (sender)))
1407   {
1408     GST_neighbours_try_connect (sender);
1409     if (NULL == (n = lookup_neighbour (sender)))
1410     {
1411       GNUNET_STATISTICS_update (GST_stats,
1412                                 gettext_noop
1413                                 ("# messages discarded due to lack of neighbour record"),
1414                                 1, GNUNET_NO);
1415       *do_forward = GNUNET_NO;
1416       return GNUNET_TIME_UNIT_ZERO;
1417     }
1418   }
1419   if (! test_connected (n))
1420   {
1421     *do_forward = GNUNET_SYSERR;
1422     return GNUNET_TIME_UNIT_ZERO;
1423   }
1424   if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, size))
1425   {
1426     n->quota_violation_count++;
1427     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1428                 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
1429                 n->in_tracker.available_bytes_per_s__,
1430                 n->quota_violation_count);
1431     /* Discount 32k per violation */
1432     GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, -32 * 1024);
1433   }
1434   else
1435   {
1436     if (n->quota_violation_count > 0)
1437     {
1438       /* try to add 32k back */
1439       GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, 32 * 1024);
1440       n->quota_violation_count--;
1441     }
1442   }
1443   if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
1444   {
1445     GNUNET_STATISTICS_update (GST_stats,
1446                               gettext_noop
1447                               ("# bandwidth quota violations by other peers"),
1448                               1, GNUNET_NO);
1449     *do_forward = GNUNET_NO;
1450     return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
1451   }
1452   *do_forward = GNUNET_YES;
1453   ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 32 * 1024);
1454   if (ret.rel_value > 0)
1455   {
1456     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1457                 "Throttling read (%llu bytes excess at %u b/s), waiting %llu ms before reading more.\n",
1458                 (unsigned long long) n->in_tracker.
1459                 consumption_since_last_update__,
1460                 (unsigned int) n->in_tracker.available_bytes_per_s__,
1461                 (unsigned long long) ret.rel_value);
1462     GNUNET_STATISTICS_update (GST_stats,
1463                               gettext_noop ("# ms throttling suggested"),
1464                               (int64_t) ret.rel_value, GNUNET_NO);
1465   }
1466   return ret;
1467 }
1468
1469
1470 /**
1471  * Transmit a message to the given target using the active connection.
1472  *
1473  * @param target destination
1474  * @param msg message to send
1475  * @param msg_size number of bytes in msg
1476  * @param timeout when to fail with timeout
1477  * @param cont function to call when done
1478  * @param cont_cls closure for 'cont'
1479  */
1480 void
1481 GST_neighbours_send (const struct GNUNET_PeerIdentity *target, const void *msg,
1482                      size_t msg_size, struct GNUNET_TIME_Relative timeout,
1483                      GST_NeighbourSendContinuation cont, void *cont_cls)
1484 {
1485   struct NeighbourMapEntry *n;
1486   struct MessageQueue *mq;
1487
1488   /* All ove these cases should never happen; they are all API violations.
1489      But we check anyway, just to be sure. */
1490   if (NULL == (n = lookup_neighbour (target)))
1491   {
1492     GNUNET_break (0);
1493     if (NULL != cont)
1494       cont (cont_cls, GNUNET_SYSERR, msg_size, 0);
1495     return;
1496   }
1497   if (GNUNET_YES != test_connected (n))
1498   {
1499     GNUNET_break (0);
1500     if (NULL != cont)
1501       cont (cont_cls, GNUNET_SYSERR, msg_size, 0);
1502     return;
1503   }
1504   bytes_in_send_queue += msg_size;
1505   GNUNET_STATISTICS_set (GST_stats,
1506                          gettext_noop
1507                          ("# bytes in message queue for other peers"),
1508                          bytes_in_send_queue, GNUNET_NO);
1509   mq = GNUNET_malloc (sizeof (struct MessageQueue) + msg_size);
1510   mq->cont = cont;
1511   mq->cont_cls = cont_cls;
1512   memcpy (&mq[1], msg, msg_size);
1513   mq->message_buf = (const char *) &mq[1];
1514   mq->message_buf_size = msg_size;
1515   mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1516   GNUNET_CONTAINER_DLL_insert_tail (n->messages_head, n->messages_tail, mq);
1517   if ( (NULL != n->is_active) ||
1518        ( (NULL == n->primary_address.session) && (NULL == n->primary_address.address)) )
1519     return;
1520   if (GNUNET_SCHEDULER_NO_TASK != n->task)
1521     GNUNET_SCHEDULER_cancel (n->task);
1522   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
1523 }
1524
1525
1526 /**
1527  * Send a SESSION_CONNECT message via the given address.
1528  *
1529  * @param na address to use
1530  */
1531 static void
1532 send_session_connect (struct NeighbourAddress *na)
1533 {
1534   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1535   struct SessionConnectMessage connect_msg;
1536
1537   if (NULL == (papi = GST_plugins_find (na->address->transport_name)))  
1538   {
1539     GNUNET_break (0);
1540     return;
1541   }
1542   if (NULL == na->session)
1543     na->session = papi->get_session (papi->cls, na->address);    
1544   if (NULL == na->session)
1545   {
1546     GNUNET_break (0);
1547     return;
1548   }
1549   na->connect_timestamp = GNUNET_TIME_absolute_get ();
1550   connect_msg.header.size = htons (sizeof (struct SessionConnectMessage));
1551   connect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT);
1552   connect_msg.reserved = htonl (0);
1553   connect_msg.timestamp = GNUNET_TIME_absolute_hton (na->connect_timestamp);
1554   (void) papi->send (papi->cls,
1555                      na->session,
1556                      (const char *) &connect_msg, sizeof (struct SessionConnectMessage),
1557                      UINT_MAX,
1558                      GNUNET_TIME_UNIT_FOREVER_REL,
1559                      NULL, NULL);
1560
1561 }
1562
1563
1564 /**
1565  * Send a SESSION_CONNECT_ACK message via the given address.
1566  *
1567  * @param address address to use
1568  * @param session session to use
1569  * @param timestamp timestamp to use for the ACK message
1570  */
1571 static void
1572 send_session_connect_ack_message (const struct GNUNET_HELLO_Address *address,
1573                                   struct Session *session,
1574                                   struct GNUNET_TIME_Absolute timestamp)
1575 {
1576   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1577   struct SessionConnectMessage connect_msg;
1578
1579   if (NULL == (papi = GST_plugins_find (address->transport_name)))  
1580   {
1581     GNUNET_break (0);
1582     return;
1583   }
1584   if (NULL == session)
1585     session = papi->get_session (papi->cls, address);    
1586   if (NULL == session)
1587   {
1588     GNUNET_break (0);
1589     return;
1590   }
1591   connect_msg.header.size = htons (sizeof (struct SessionConnectMessage));
1592   connect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT_ACK);
1593   connect_msg.reserved = htonl (0);
1594   connect_msg.timestamp = GNUNET_TIME_absolute_hton (timestamp);
1595   (void) papi->send (papi->cls,
1596                      session,
1597                      (const char *) &connect_msg, sizeof (struct SessionConnectMessage),
1598                      UINT_MAX,
1599                      GNUNET_TIME_UNIT_FOREVER_REL,
1600                      NULL, NULL);
1601
1602 }
1603
1604
1605 /**
1606  * Create a fresh entry in the neighbour map for the given peer
1607  *
1608  * @param peer peer to create an entry for
1609  * @return new neighbour map entry
1610  */
1611 static struct NeighbourMapEntry *
1612 setup_neighbour (const struct GNUNET_PeerIdentity *peer)
1613 {
1614   struct NeighbourMapEntry *n;
1615
1616   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1617               "Creating new neighbour entry for `%s'\n", 
1618               GNUNET_i2s (peer));
1619   n = GNUNET_malloc (sizeof (struct NeighbourMapEntry));
1620   n->id = *peer;
1621   n->state = S_NOT_CONNECTED;
1622   n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
1623   GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
1624                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
1625                                  MAX_BANDWIDTH_CARRY_S);
1626   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
1627   GNUNET_assert (GNUNET_OK ==
1628                  GNUNET_CONTAINER_multihashmap_put (neighbours,
1629                                                     &n->id.hashPubKey, n,
1630                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1631   return n;
1632 }
1633
1634
1635 /**
1636  * Check if the two given addresses are the same.
1637  * Actually only checks if the sessions are non-NULL
1638  * (which they should be) and then if they are identical;
1639  * the actual addresses don't matter if the session
1640  * pointers match anyway, and we must have session pointers
1641  * at this time.
1642  *
1643  * @param a1 first address to compare
1644  * @param a2 other address to compare
1645  * @return GNUNET_NO if the addresses do not match, GNUNET_YES if they do match
1646  */
1647 static int
1648 address_matches (const struct NeighbourAddress *a1,
1649                  const struct NeighbourAddress *a2)
1650 {
1651   if ( (NULL == a1->session) ||
1652        (NULL == a2->session) )
1653   {
1654     GNUNET_break (0);
1655     return 0;
1656   }
1657   return (a1->session == a2->session) ? GNUNET_YES : GNUNET_NO;
1658 }
1659
1660
1661 /**
1662  * Try to create a connection to the given target (eventually).
1663  *
1664  * @param target peer to try to connect to
1665  */
1666 void
1667 GST_neighbours_try_connect (const struct GNUNET_PeerIdentity *target)
1668 {
1669   struct NeighbourMapEntry *n;
1670
1671   if (NULL == neighbours)  
1672     return; /* during shutdown, do nothing */
1673   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1674               "Asked to connect to peer `%s'\n",
1675               GNUNET_i2s (target));
1676   if (0 ==
1677       memcmp (target, &GST_my_identity, sizeof (struct GNUNET_PeerIdentity)))
1678   {
1679     /* refuse to connect to myself */
1680     /* FIXME: can this happen? Is this not an API violation? */
1681     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1682                 "Refusing to try to connect to myself.\n");
1683     return;
1684   }
1685   n = lookup_neighbour (target);
1686   if (NULL != n)
1687   {
1688     switch (n->state)
1689     {
1690     case S_NOT_CONNECTED:
1691       /* this should not be possible */
1692       GNUNET_break (0);
1693       free_neighbour (n, GNUNET_NO);
1694       break;
1695     case S_INIT_ATS:
1696     case S_INIT_BLACKLIST:
1697     case S_CONNECT_SENT:
1698     case S_CONNECT_RECV_BLACKLIST_INBOUND:
1699     case S_CONNECT_RECV_ATS:
1700     case S_CONNECT_RECV_BLACKLIST:
1701     case S_CONNECT_RECV_ACK:
1702       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1703                   "Ignoring request to try to connect to `%s', already trying!\n",
1704                   GNUNET_i2s (target));
1705       return; /* already trying */
1706     case S_CONNECTED:      
1707     case S_RECONNECT_ATS:
1708     case S_RECONNECT_BLACKLIST:
1709     case S_RECONNECT_SENT:
1710     case S_CONNECTED_SWITCHING_BLACKLIST:
1711     case S_CONNECTED_SWITCHING_CONNECT_SENT:
1712       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1713                   "Ignoring request to try to connect, already connected to `%s'!\n",
1714                   GNUNET_i2s (target));
1715       return; /* already connected */
1716     case S_DISCONNECT:
1717       /* get rid of remains, ready to re-try immediately */
1718       free_neighbour (n, GNUNET_NO);
1719       break;
1720     case S_DISCONNECT_FINISHED:
1721       /* should not be possible */      
1722       GNUNET_assert (0); 
1723     default:
1724       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
1725       GNUNET_break (0);
1726       free_neighbour (n, GNUNET_NO);
1727       break;
1728     }
1729   }
1730   n = setup_neighbour (target);  
1731   n->state = S_INIT_ATS; 
1732   n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1733
1734   GNUNET_ATS_reset_backoff (GST_ats, target);
1735   GNUNET_ATS_suggest_address (GST_ats, target);
1736 }
1737
1738
1739 /**
1740  * Function called with the result of a blacklist check.
1741  *
1742  * @param cls closure with the 'struct BlackListCheckContext'
1743  * @param peer peer this check affects
1744  * @param result GNUNET_OK if the address is allowed
1745  */
1746 static void
1747 handle_test_blacklist_cont (void *cls,
1748                             const struct GNUNET_PeerIdentity *peer,
1749                             int result)
1750 {
1751   struct BlackListCheckContext *bcc = cls;
1752   struct NeighbourMapEntry *n;
1753
1754   bcc->bc = NULL;
1755   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1756               "Connection to new address of peer `%s' based on blacklist is `%s'\n",
1757               GNUNET_i2s (peer),
1758               (GNUNET_OK == result) ? "allowed" : "FORBIDDEN");
1759   if (NULL == (n = lookup_neighbour (peer)))
1760     goto cleanup; /* nobody left to care about new address */
1761   switch (n->state)
1762   {
1763   case S_NOT_CONNECTED:
1764     /* this should not be possible */
1765     GNUNET_break (0);
1766     free_neighbour (n, GNUNET_NO);
1767     break;
1768   case S_INIT_ATS:
1769     /* still waiting on ATS suggestion */
1770     break;
1771   case S_INIT_BLACKLIST:
1772     /* check if the address the blacklist was fine with matches
1773        ATS suggestion, if so, we can move on! */
1774     if ( (GNUNET_OK == result) &&
1775          (1 == n->send_connect_ack) )
1776     {
1777       n->send_connect_ack = 2;
1778       send_session_connect_ack_message (bcc->na.address,
1779                                         bcc->na.session,
1780                                         n->connect_ack_timestamp);
1781     }
1782     if (GNUNET_YES != address_matches (&bcc->na, &n->primary_address))
1783       break; /* result for an address we currently don't care about */
1784     if (GNUNET_OK == result)
1785     {
1786       n->timeout = GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT);
1787       n->state = S_CONNECT_SENT;
1788       send_session_connect (&n->primary_address);
1789     }
1790     else
1791     {
1792       // FIXME: should also possibly destroy session with plugin!?
1793       GNUNET_ATS_address_destroyed (GST_ats,
1794                                     bcc->na.address,
1795                                     NULL);
1796       free_address (&n->primary_address);
1797       n->state = S_INIT_ATS;
1798       n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1799       // FIXME: do we need to ask ATS again for suggestions?
1800       GNUNET_ATS_suggest_address (GST_ats, &n->id);
1801     }
1802     break;
1803   case S_CONNECT_SENT:
1804     /* waiting on CONNECT_ACK, send ACK if one is pending */
1805     if ( (GNUNET_OK == result) &&
1806          (1 == n->send_connect_ack) )
1807     {
1808       n->send_connect_ack = 2;
1809       send_session_connect_ack_message (n->primary_address.address,
1810                                         n->primary_address.session,
1811                                         n->connect_ack_timestamp);
1812     }
1813     break; 
1814   case S_CONNECT_RECV_BLACKLIST_INBOUND:
1815     if (GNUNET_OK == result)
1816     {
1817       /* valid new address, let ATS know! */
1818       GNUNET_ATS_address_add (GST_ats,
1819                               bcc->na.address,
1820                               bcc->na.session,
1821                               bcc->ats, bcc->ats_count);
1822     }
1823     n->state = S_CONNECT_RECV_ATS;
1824     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1825     GNUNET_ATS_reset_backoff (GST_ats, peer);
1826     GNUNET_ATS_suggest_address (GST_ats, peer);
1827     break;
1828   case S_CONNECT_RECV_ATS:
1829     /* still waiting on ATS suggestion, don't care about blacklist */
1830     break;
1831   case S_CONNECT_RECV_BLACKLIST:
1832     if (GNUNET_YES != address_matches (&bcc->na, &n->primary_address))
1833       break; /* result for an address we currently don't care about */
1834     if (GNUNET_OK == result)
1835     {
1836       n->timeout = GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT);
1837       n->state = S_CONNECT_RECV_ACK;
1838       send_session_connect_ack_message (bcc->na.address,
1839                                         bcc->na.session,
1840                                         n->connect_ack_timestamp);
1841       if (1 == n->send_connect_ack) 
1842         n->send_connect_ack = 2;
1843     }
1844     else
1845     {
1846       // FIXME: should also possibly destroy session with plugin!?
1847       GNUNET_ATS_address_destroyed (GST_ats,
1848                                     bcc->na.address,
1849                                     NULL);
1850       free_address (&n->primary_address);
1851       n->state = S_INIT_ATS;
1852       n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1853       // FIXME: do we need to ask ATS again for suggestions?
1854       GNUNET_ATS_reset_backoff (GST_ats, peer);
1855       GNUNET_ATS_suggest_address (GST_ats, &n->id);
1856     }
1857     break;
1858   case S_CONNECT_RECV_ACK:
1859     /* waiting on SESSION_ACK, send ACK if one is pending */
1860     if ( (GNUNET_OK == result) &&
1861          (1 == n->send_connect_ack) )
1862     {
1863       n->send_connect_ack = 2;
1864       send_session_connect_ack_message (n->primary_address.address,
1865                                         n->primary_address.session,
1866                                         n->connect_ack_timestamp);
1867     }
1868     break; 
1869   case S_CONNECTED:
1870     /* already connected, don't care about blacklist */
1871     break;
1872   case S_RECONNECT_ATS:
1873     /* still waiting on ATS suggestion, don't care about blacklist */
1874     break;     
1875   case S_RECONNECT_BLACKLIST:
1876     if ( (GNUNET_OK == result) &&
1877          (1 == n->send_connect_ack) )
1878     {
1879       n->send_connect_ack = 2;
1880       send_session_connect_ack_message (bcc->na.address,
1881                                         bcc->na.session,
1882                                         n->connect_ack_timestamp);
1883     }
1884     if (GNUNET_YES != address_matches (&bcc->na, &n->primary_address))
1885       break; /* result for an address we currently don't care about */
1886     if (GNUNET_OK == result)
1887     {
1888       send_session_connect (&n->primary_address);
1889       n->timeout = GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT);
1890       n->state = S_RECONNECT_SENT;
1891     }
1892     else
1893     {
1894       GNUNET_ATS_address_destroyed (GST_ats,
1895                                     bcc->na.address,
1896                                     NULL);
1897       n->state = S_RECONNECT_ATS;
1898       n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1899       // FIXME: do we need to ask ATS again for suggestions?
1900       GNUNET_ATS_suggest_address (GST_ats, &n->id);
1901     }
1902     break;
1903   case S_RECONNECT_SENT:
1904     /* waiting on CONNECT_ACK, don't care about blacklist */
1905     if ( (GNUNET_OK == result) &&
1906          (1 == n->send_connect_ack) )
1907     {
1908       n->send_connect_ack = 2;
1909       send_session_connect_ack_message (n->primary_address.address,
1910                                         n->primary_address.session,
1911                                         n->connect_ack_timestamp);
1912     }
1913     break;     
1914   case S_CONNECTED_SWITCHING_BLACKLIST:
1915     if (GNUNET_YES != address_matches (&bcc->na, &n->alternative_address))
1916       break; /* result for an address we currently don't care about */
1917     if (GNUNET_OK == result)
1918     {
1919       send_session_connect (&n->alternative_address);
1920       n->state = S_CONNECTED_SWITCHING_CONNECT_SENT;
1921     }
1922     else
1923     {
1924       GNUNET_ATS_address_destroyed (GST_ats,
1925                                     bcc->na.address,
1926                                     NULL);
1927       free_address (&n->alternative_address);
1928       n->state = S_CONNECTED;
1929     }
1930     break;
1931   case S_CONNECTED_SWITCHING_CONNECT_SENT:
1932     /* waiting on CONNECT_ACK, don't care about blacklist */
1933     if ( (GNUNET_OK == result) &&
1934          (1 == n->send_connect_ack) )
1935     {
1936       n->send_connect_ack = 2;
1937       send_session_connect_ack_message (n->primary_address.address,
1938                                         n->primary_address.session,
1939                                         n->connect_ack_timestamp);
1940     }
1941     break;     
1942   case S_DISCONNECT:
1943     /* Nothing to do here, ATS will already do what can be done */
1944     break;
1945   case S_DISCONNECT_FINISHED:
1946     /* should not be possible */
1947     GNUNET_assert (0);
1948     break;
1949   default:
1950     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
1951     GNUNET_break (0);
1952     free_neighbour (n, GNUNET_NO);
1953     break;
1954   }
1955  cleanup:
1956   GNUNET_HELLO_address_free (bcc->na.address);
1957   GNUNET_CONTAINER_DLL_remove (bc_head,
1958                                bc_tail,
1959                                bcc);
1960   GNUNET_free (bcc);
1961 }
1962
1963
1964 /**
1965  * We want to know if connecting to a particular peer via
1966  * a particular address is allowed.  Check it!
1967  *
1968  * @param peer identity of the peer to switch the address for
1969  * @param ts time at which the check was initiated
1970  * @param address address of the other peer, NULL if other peer
1971  *                       connected to us
1972  * @param session session to use (or NULL)
1973  * @param ats performance data
1974  * @param ats_count number of entries in ats (excluding 0-termination)
1975  */
1976 static void
1977 check_blacklist (const struct GNUNET_PeerIdentity *peer,
1978                  struct GNUNET_TIME_Absolute ts,
1979                  const struct GNUNET_HELLO_Address *address,
1980                  struct Session *session,
1981                  const struct GNUNET_ATS_Information *ats,
1982                  uint32_t ats_count)
1983 {
1984   struct BlackListCheckContext *bcc;
1985   struct GST_BlacklistCheck *bc;
1986
1987   bcc =
1988       GNUNET_malloc (sizeof (struct BlackListCheckContext) +
1989                      sizeof (struct GNUNET_ATS_Information) * ats_count);
1990   bcc->ats_count = ats_count;
1991   bcc->na.address = GNUNET_HELLO_address_copy (address);
1992   bcc->na.session = session;
1993   bcc->na.connect_timestamp = ts;
1994   bcc->ats = (struct GNUNET_ATS_Information *) &bcc[1];
1995   memcpy (bcc->ats, ats, sizeof (struct GNUNET_ATS_Information) * ats_count);
1996   GNUNET_CONTAINER_DLL_insert (bc_head,
1997                                bc_tail,
1998                                bcc);
1999   if (NULL != (bc = GST_blacklist_test_allowed (peer, 
2000                                                 address->transport_name,
2001                                                 &handle_test_blacklist_cont, bcc)))
2002     bcc->bc = bc; 
2003   /* if NULL == bc, 'cont' was already called and 'bcc' already free'd, so
2004      we must only store 'bc' if 'bc' is non-NULL... */
2005 }
2006
2007
2008 /**
2009  * We received a 'SESSION_CONNECT' message from the other peer.
2010  * Consider switching to it.
2011  *
2012  * @param message possibly a 'struct SessionConnectMessage' (check format)
2013  * @param peer identity of the peer to switch the address for
2014  * @param address address of the other peer, NULL if other peer
2015  *                       connected to us
2016  * @param session session to use (or NULL)
2017  * @param ats performance data
2018  * @param ats_count number of entries in ats (excluding 0-termination)
2019  */
2020 void
2021 GST_neighbours_handle_connect (const struct GNUNET_MessageHeader *message,
2022                                const struct GNUNET_PeerIdentity *peer,
2023                                const struct GNUNET_HELLO_Address *address,
2024                                struct Session *session,
2025                                const struct GNUNET_ATS_Information *ats,
2026                                uint32_t ats_count)
2027 {
2028   const struct SessionConnectMessage *scm;
2029   struct NeighbourMapEntry *n;
2030   struct GNUNET_TIME_Absolute ts;
2031
2032   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2033               "Received CONNECT message from peer `%s'\n", 
2034               GNUNET_i2s (peer));
2035
2036   if (ntohs (message->size) != sizeof (struct SessionConnectMessage))
2037   {
2038     GNUNET_break_op (0);
2039     return;
2040   }
2041   if (NULL == neighbours)
2042     return; /* we're shutting down */
2043   scm = (const struct SessionConnectMessage *) message;
2044   GNUNET_break_op (0 == ntohl (scm->reserved));
2045   ts = GNUNET_TIME_absolute_ntoh (scm->timestamp);
2046   n = lookup_neighbour (peer);
2047   if (NULL == n)
2048     n = setup_neighbour (peer);
2049   n->send_connect_ack = 1;
2050   n->connect_ack_timestamp = ts;
2051
2052   switch (n->state)
2053   {  
2054   case S_NOT_CONNECTED:
2055     n->state = S_CONNECT_RECV_BLACKLIST_INBOUND;
2056     /* Do a blacklist check for the new address */
2057     check_blacklist (peer, ts, address, session, ats, ats_count);
2058     break;
2059   case S_INIT_ATS:
2060     /* CONNECT message takes priority over us asking ATS for address */
2061     n->state = S_CONNECT_RECV_BLACKLIST_INBOUND;
2062     /* fallthrough */
2063   case S_INIT_BLACKLIST:
2064   case S_CONNECT_SENT:
2065   case S_CONNECT_RECV_BLACKLIST_INBOUND:
2066   case S_CONNECT_RECV_ATS:
2067   case S_CONNECT_RECV_BLACKLIST:
2068   case S_CONNECT_RECV_ACK:
2069     /* It can never hurt to have an alternative address in the above cases, 
2070        see if it is allowed */
2071     check_blacklist (peer, ts, address, session, ats, ats_count);
2072     break;
2073   case S_CONNECTED:
2074     /* we are already connected and can thus send the ACK immediately;
2075        still, it can never hurt to have an alternative address, so also
2076        tell ATS  about it */
2077     GNUNET_assert (NULL != n->primary_address.address);
2078     GNUNET_assert (NULL != n->primary_address.session);
2079     n->send_connect_ack = 0;
2080     send_session_connect_ack_message (n->primary_address.address,
2081                                       n->primary_address.session, ts);
2082     check_blacklist (peer, ts, address, session, ats, ats_count);
2083     break;
2084   case S_RECONNECT_ATS:
2085   case S_RECONNECT_BLACKLIST:
2086   case S_RECONNECT_SENT:
2087     /* It can never hurt to have an alternative address in the above cases, 
2088        see if it is allowed */
2089     check_blacklist (peer, ts, address, session, ats, ats_count);
2090     break;
2091   case S_CONNECTED_SWITCHING_BLACKLIST:
2092   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2093     /* we are already connected and can thus send the ACK immediately;
2094        still, it can never hurt to have an alternative address, so also
2095        tell ATS  about it */
2096     GNUNET_assert (NULL != n->primary_address.address);
2097     GNUNET_assert (NULL != n->primary_address.session);
2098     n->send_connect_ack = 0;
2099     send_session_connect_ack_message (n->primary_address.address,
2100                                       n->primary_address.session, ts);
2101     check_blacklist (peer, ts, address, session, ats, ats_count);
2102     break;
2103   case S_DISCONNECT:
2104     /* get rid of remains without terminating sessions, ready to re-try */
2105     free_neighbour (n, GNUNET_YES);
2106     n = setup_neighbour (peer);
2107     n->state = S_CONNECT_RECV_ATS;
2108     GNUNET_ATS_reset_backoff (GST_ats, peer);
2109     GNUNET_ATS_suggest_address (GST_ats, peer);
2110     break;
2111   case S_DISCONNECT_FINISHED:
2112     /* should not be possible */
2113     GNUNET_assert (0);
2114     break;
2115   default:
2116     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2117     GNUNET_break (0);
2118     free_neighbour (n, GNUNET_NO);
2119     break;
2120   }
2121 }
2122
2123
2124 /**
2125  * For an existing neighbour record, set the active connection to
2126  * use the given address.  
2127  *
2128  * @param peer identity of the peer to switch the address for
2129  * @param address address of the other peer, NULL if other peer
2130  *                       connected to us
2131  * @param session session to use (or NULL)
2132  * @param ats performance data
2133  * @param ats_count number of entries in ats
2134  * @param bandwidth_in inbound quota to be used when connection is up
2135  * @param bandwidth_out outbound quota to be used when connection is up
2136  */
2137 void
2138 GST_neighbours_switch_to_address (const struct GNUNET_PeerIdentity *peer,
2139                                   const struct GNUNET_HELLO_Address *address,
2140                                   struct Session *session,
2141                                   const struct GNUNET_ATS_Information *ats,
2142                                   uint32_t ats_count,
2143                                   struct GNUNET_BANDWIDTH_Value32NBO
2144                                   bandwidth_in,
2145                                   struct GNUNET_BANDWIDTH_Value32NBO
2146                                   bandwidth_out)
2147 {
2148   struct NeighbourMapEntry *n;
2149   struct GNUNET_TRANSPORT_PluginFunctions *papi;
2150
2151   GNUNET_assert (address->transport_name != NULL);
2152   if (NULL == (n = lookup_neighbour (peer)))
2153     return;
2154
2155   /* Obtain an session for this address from plugin */
2156   if (NULL == (papi = GST_plugins_find (address->transport_name)))
2157   {
2158     /* we don't have the plugin for this address */
2159     GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
2160     return;
2161   }
2162   if ((NULL == session) && (0 == address->address_length))
2163   {
2164     GNUNET_break (0);
2165     if (strlen (address->transport_name) > 0)
2166       GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
2167     return;
2168   }
2169
2170   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2171               "ATS tells us to switch to address '%s' session %p for "
2172               "peer `%s' in state %s (quota in/out %u %u )\n",
2173               (address->address_length != 0) ? GST_plugins_a2s (address): "<inbound>",
2174               session,
2175               GNUNET_i2s (peer),
2176               print_state (n->state),
2177               ntohl (bandwidth_in.value__),
2178               ntohl (bandwidth_out.value__));
2179
2180   if (NULL == session)
2181   {
2182     session = papi->get_session (papi->cls, address);
2183     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2184                 "Obtained new session for peer `%s' and  address '%s': %p\n",
2185                 GNUNET_i2s (&address->peer), GST_plugins_a2s (address), session);
2186   }
2187   if (NULL == session)
2188   {
2189     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2190                 "Failed to obtain new session for peer `%s' and  address '%s'\n",
2191                 GNUNET_i2s (&address->peer), GST_plugins_a2s (address));    
2192     GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
2193     return;
2194   }
2195   switch (n->state)
2196   {
2197   case S_NOT_CONNECTED:
2198     GNUNET_break (0);
2199     free_neighbour (n, GNUNET_NO);
2200     return;
2201   case S_INIT_ATS:
2202     set_address (&n->primary_address,
2203                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2204     n->state = S_INIT_BLACKLIST;
2205     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2206     check_blacklist (&n->id,
2207                      n->connect_ack_timestamp,
2208                      address, session, ats, ats_count);    
2209     break;
2210   case S_INIT_BLACKLIST:
2211     /* ATS suggests a different address, switch again */
2212     set_address (&n->primary_address,
2213                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2214     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2215     check_blacklist (&n->id,
2216                      n->connect_ack_timestamp,
2217                      address, session, ats, ats_count);    
2218     break;
2219   case S_CONNECT_SENT:
2220     /* ATS suggests a different address, switch again */
2221     set_address (&n->primary_address,
2222                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2223     n->state = S_INIT_BLACKLIST;
2224     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2225     check_blacklist (&n->id,
2226                      n->connect_ack_timestamp,
2227                      address, session, ats, ats_count);    
2228     break;
2229   case S_CONNECT_RECV_ATS:
2230     set_address (&n->primary_address,
2231                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2232     n->state = S_CONNECT_RECV_BLACKLIST;
2233     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2234     check_blacklist (&n->id,
2235                      n->connect_ack_timestamp,
2236                      address, session, ats, ats_count);    
2237     break;
2238   case S_CONNECT_RECV_BLACKLIST_INBOUND:
2239     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2240     check_blacklist (&n->id,
2241                      n->connect_ack_timestamp,
2242                      address, session, ats, ats_count);
2243     break;
2244   case S_CONNECT_RECV_BLACKLIST:
2245   case S_CONNECT_RECV_ACK:
2246     /* ATS asks us to switch while we were trying to connect; switch to new
2247        address and check blacklist again */
2248     set_address (&n->primary_address,
2249                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2250     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2251     check_blacklist (&n->id,
2252                      n->connect_ack_timestamp,
2253                      address, session, ats, ats_count);    
2254     break;
2255   case S_CONNECTED:
2256     GNUNET_assert (NULL != n->primary_address.address);
2257     GNUNET_assert (NULL != n->primary_address.session);
2258     if (n->primary_address.session == session)
2259     {
2260       /* not an address change, just a quota change */
2261       set_address (&n->primary_address,
2262                    address, session, bandwidth_in, bandwidth_out, GNUNET_YES);
2263       break;
2264     }
2265     /* ATS asks us to switch a life connection; see if we can get
2266        a CONNECT_ACK on it before we actually do this! */
2267     set_address (&n->alternative_address,
2268                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2269     n->state = S_CONNECTED_SWITCHING_BLACKLIST;
2270     check_blacklist (&n->id,
2271                      GNUNET_TIME_absolute_get (),
2272                      address, session, ats, ats_count);
2273     break;
2274   case S_RECONNECT_ATS:
2275     set_address (&n->primary_address,
2276                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2277     n->state = S_RECONNECT_BLACKLIST;
2278     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2279     check_blacklist (&n->id,
2280                      n->connect_ack_timestamp,
2281                      address, session, ats, ats_count);    
2282     break;
2283   case S_RECONNECT_BLACKLIST:
2284     /* ATS asks us to switch while we were trying to reconnect; switch to new
2285        address and check blacklist again */
2286     set_address (&n->primary_address,
2287                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2288     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2289     check_blacklist (&n->id,
2290                      n->connect_ack_timestamp,
2291                      address, session, ats, ats_count);    
2292     break;
2293   case S_RECONNECT_SENT:
2294     /* ATS asks us to switch while we were trying to reconnect; switch to new
2295        address and check blacklist again */
2296     set_address (&n->primary_address,
2297                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2298     n->state = S_RECONNECT_BLACKLIST;
2299     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2300     check_blacklist (&n->id,
2301                      n->connect_ack_timestamp,
2302                      address, session, ats, ats_count); 
2303     break;
2304   case S_CONNECTED_SWITCHING_BLACKLIST:
2305     if (n->primary_address.session == session)
2306     {
2307       /* ATS switches back to still-active session */
2308       free_address (&n->alternative_address);
2309       n->state = S_CONNECTED;
2310       break;
2311     }
2312     /* ATS asks us to switch a life connection, update blacklist check */
2313     set_address (&n->alternative_address,
2314                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2315     check_blacklist (&n->id,
2316                      GNUNET_TIME_absolute_get (),
2317                      address, session, ats, ats_count);
2318     break;
2319   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2320     if (n->primary_address.session == session)
2321     {
2322       /* ATS switches back to still-active session */
2323       free_address (&n->alternative_address);
2324       n->state = S_CONNECTED;
2325       break;
2326     }
2327     /* ATS asks us to switch a life connection, update blacklist check */
2328     set_address (&n->alternative_address,
2329                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2330     n->state = S_CONNECTED_SWITCHING_BLACKLIST;
2331     check_blacklist (&n->id,
2332                      GNUNET_TIME_absolute_get (),
2333                      address, session, ats, ats_count);
2334     break;
2335   case S_DISCONNECT:
2336     /* not going to switch addresses while disconnecting */
2337     return;
2338   case S_DISCONNECT_FINISHED:
2339     GNUNET_assert (0);
2340     break;
2341   default:
2342     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2343     GNUNET_break (0);
2344     break;
2345   }
2346 }
2347
2348
2349 /**
2350  * Master task run for every neighbour.  Performs all of the time-related
2351  * activities (keep alive, send next message, disconnect if idle, finish
2352  * clean up after disconnect).
2353  *
2354  * @param cls the 'struct NeighbourMapEntry' for which we are running
2355  * @param tc scheduler context (unused)
2356  */
2357 static void
2358 master_task (void *cls,
2359              const struct GNUNET_SCHEDULER_TaskContext *tc)
2360 {
2361   struct NeighbourMapEntry *n = cls;
2362   struct GNUNET_TIME_Relative delay;
2363
2364   n->task = GNUNET_SCHEDULER_NO_TASK;
2365   delay = GNUNET_TIME_absolute_get_remaining (n->timeout);  
2366   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2367               "Master task runs for neighbour `%s' in state %s with timeout in %llu ms\n",
2368               GNUNET_i2s (&n->id),
2369               print_state(n->state),
2370               (unsigned long long) delay.rel_value);
2371   switch (n->state)
2372   {
2373   case S_NOT_CONNECTED:
2374     /* invalid state for master task, clean up */
2375     GNUNET_break (0);
2376     n->state = S_DISCONNECT_FINISHED;
2377     free_neighbour (n, GNUNET_NO);
2378     return;
2379   case S_INIT_ATS:
2380     if (0 == delay.rel_value)
2381     {
2382       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2383                   "Connection to `%s' timed out waiting for ATS to provide address\n",
2384                   GNUNET_i2s (&n->id));
2385       n->state = S_DISCONNECT_FINISHED;
2386       free_neighbour (n, GNUNET_NO);
2387       return;
2388     }
2389     break;
2390   case S_INIT_BLACKLIST:
2391     if (0 == delay.rel_value)
2392     {
2393       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2394                   "Connection to `%s' timed out waiting for BLACKLIST to approve address\n",
2395                   GNUNET_i2s (&n->id));
2396       n->state = S_DISCONNECT_FINISHED;
2397       free_neighbour (n, GNUNET_NO);
2398       return;
2399     }
2400     break;
2401   case S_CONNECT_SENT:
2402     if (0 == delay.rel_value)
2403     {
2404       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2405                   "Connection to `%s' timed out waiting for other peer to send CONNECT_ACK\n",
2406                   GNUNET_i2s (&n->id));
2407       disconnect_neighbour (n);
2408       return;
2409     }
2410     break;
2411   case S_CONNECT_RECV_BLACKLIST_INBOUND:
2412     if (0 == delay.rel_value)
2413     {
2414       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2415                   "Connection to `%s' timed out waiting BLACKLIST to approve address to use for received CONNECT\n",
2416                   GNUNET_i2s (&n->id));
2417       n->state = S_DISCONNECT_FINISHED;
2418       free_neighbour (n, GNUNET_NO);
2419       return;
2420     }
2421     break;
2422   case S_CONNECT_RECV_ATS:
2423     if (0 == delay.rel_value)
2424     {
2425       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2426                   "Connection to `%s' timed out waiting ATS to provide address to use for CONNECT_ACK\n",
2427                   GNUNET_i2s (&n->id));
2428       n->state = S_DISCONNECT_FINISHED;
2429       free_neighbour (n, GNUNET_NO);
2430       return;
2431     }
2432     break;
2433   case S_CONNECT_RECV_BLACKLIST:
2434     if (0 == delay.rel_value)
2435     {
2436       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2437                   "Connection to `%s' timed out waiting BLACKLIST to approve address to use for CONNECT_ACK\n",
2438                   GNUNET_i2s (&n->id));
2439       n->state = S_DISCONNECT_FINISHED;
2440       free_neighbour (n, GNUNET_NO);
2441       return;
2442     }
2443     break;
2444   case S_CONNECT_RECV_ACK:
2445     if (0 == delay.rel_value)
2446     {
2447       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2448                   "Connection to `%s' timed out waiting for other peer to send SESSION_ACK\n",
2449                   GNUNET_i2s (&n->id));
2450       disconnect_neighbour (n);
2451       return;
2452     }
2453     break;
2454   case S_CONNECTED:
2455     if (0 == delay.rel_value)
2456     {
2457       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2458                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs\n",
2459                   GNUNET_i2s (&n->id));
2460       disconnect_neighbour (n);
2461       return;
2462     }
2463     try_transmission_to_peer (n);
2464     send_keepalive (n);
2465     break;
2466   case S_RECONNECT_ATS:
2467     if (0 == delay.rel_value)
2468     {
2469       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2470                   "Connection to `%s' timed out, waiting for ATS replacement address\n",
2471                   GNUNET_i2s (&n->id));
2472       disconnect_neighbour (n);
2473       return;
2474     }
2475     break;
2476   case S_RECONNECT_BLACKLIST:
2477     if (0 == delay.rel_value)
2478     {
2479       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2480                   "Connection to `%s' timed out, waiting for BLACKLIST to approve replacement address\n",
2481                   GNUNET_i2s (&n->id));
2482       disconnect_neighbour (n);
2483       return;
2484     }
2485     break;
2486   case S_RECONNECT_SENT:
2487     if (0 == delay.rel_value)
2488     {
2489       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2490                   "Connection to `%s' timed out, waiting for other peer to CONNECT_ACK replacement address\n",
2491                   GNUNET_i2s (&n->id));
2492       disconnect_neighbour (n);
2493       return;
2494     }
2495     break;
2496   case S_CONNECTED_SWITCHING_BLACKLIST:
2497     if (0 == delay.rel_value)
2498     {
2499       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2500                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs\n",
2501                   GNUNET_i2s (&n->id));
2502       disconnect_neighbour (n);
2503       return;
2504     }
2505     try_transmission_to_peer (n);
2506     send_keepalive (n);
2507     break;
2508   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2509     if (0 == delay.rel_value)
2510     {
2511       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2512                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs (after trying to CONNECT on alternative address)\n",
2513                   GNUNET_i2s (&n->id));
2514       disconnect_neighbour (n);
2515       return;
2516     }
2517     try_transmission_to_peer (n);
2518     send_keepalive (n);
2519     break;
2520   case S_DISCONNECT:
2521     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2522                 "Cleaning up connection to `%s' after sending DISCONNECT\n",
2523                 GNUNET_i2s (&n->id));
2524     free_neighbour (n, GNUNET_NO);
2525     return;
2526   case S_DISCONNECT_FINISHED:
2527     /* how did we get here!? */
2528     GNUNET_assert (0);
2529     break;
2530   default:
2531     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2532     GNUNET_break (0);
2533     break;  
2534   }
2535   if ( (S_CONNECTED_SWITCHING_CONNECT_SENT == n->state) ||
2536        (S_CONNECTED_SWITCHING_BLACKLIST == n->state) ||
2537        (S_CONNECTED == n->state) )    
2538   {
2539     /* if we are *now* in one of these three states, we're sending
2540        keep alive messages, so we need to consider the keepalive
2541        delay, not just the connection timeout */
2542     delay = GNUNET_TIME_relative_min (GNUNET_TIME_absolute_get_remaining (n->keep_alive_time),
2543                                       delay);
2544   }
2545   if (GNUNET_SCHEDULER_NO_TASK == n->task)
2546     n->task = GNUNET_SCHEDULER_add_delayed (delay,
2547                                             &master_task,
2548                                             n);
2549 }
2550
2551
2552 /**
2553  * Send a SESSION_ACK message to the neighbour to confirm that we
2554  * got his CONNECT_ACK.
2555  *
2556  * @param n neighbour to send the SESSION_ACK to
2557  */
2558 static void
2559 send_session_ack_message (struct NeighbourMapEntry *n)
2560 {
2561   struct GNUNET_MessageHeader msg;
2562
2563   msg.size = htons (sizeof (struct GNUNET_MessageHeader));
2564   msg.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_ACK);
2565   (void) send_with_session(n,
2566                            (const char *) &msg, sizeof (struct GNUNET_MessageHeader),
2567                            UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_REL,
2568                            NULL, NULL);
2569 }
2570
2571
2572 /**
2573  * We received a 'SESSION_CONNECT_ACK' message from the other peer.
2574  * Consider switching to it.
2575  *
2576  * @param message possibly a 'struct SessionConnectMessage' (check format)
2577  * @param peer identity of the peer to switch the address for
2578  * @param address address of the other peer, NULL if other peer
2579  *                       connected to us
2580  * @param session session to use (or NULL)
2581  * @param ats performance data
2582  * @param ats_count number of entries in ats
2583  */
2584 void
2585 GST_neighbours_handle_connect_ack (const struct GNUNET_MessageHeader *message,
2586                                    const struct GNUNET_PeerIdentity *peer,
2587                                    const struct GNUNET_HELLO_Address *address,
2588                                    struct Session *session,
2589                                    const struct GNUNET_ATS_Information *ats,
2590                                    uint32_t ats_count)
2591 {
2592   const struct SessionConnectMessage *scm;
2593   struct GNUNET_TIME_Absolute ts;
2594   struct NeighbourMapEntry *n;
2595
2596   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2597               "Received CONNECT_ACK message from peer `%s'\n",
2598               GNUNET_i2s (peer));
2599
2600   if (ntohs (message->size) != sizeof (struct SessionConnectMessage))
2601   {
2602     GNUNET_break_op (0);
2603     return;
2604   }
2605   scm = (const struct SessionConnectMessage *) message;
2606   GNUNET_break_op (ntohl (scm->reserved) == 0);
2607   if (NULL == (n = lookup_neighbour (peer)))
2608   {
2609     GNUNET_STATISTICS_update (GST_stats,
2610                               gettext_noop
2611                               ("# unexpected CONNECT_ACK messages (no peer)"),
2612                               1, GNUNET_NO);
2613     return;
2614   }
2615   ts = GNUNET_TIME_absolute_ntoh (scm->timestamp);
2616   switch (n->state)
2617   {
2618   case S_NOT_CONNECTED:
2619     GNUNET_break (0);
2620     free_neighbour (n, GNUNET_NO);
2621     return;
2622   case S_INIT_ATS:
2623   case S_INIT_BLACKLIST:
2624     GNUNET_STATISTICS_update (GST_stats,
2625                               gettext_noop
2626                               ("# unexpected CONNECT_ACK messages (not ready)"),
2627                               1, GNUNET_NO);
2628     break;    
2629   case S_CONNECT_SENT:
2630     if (ts.abs_value != n->primary_address.connect_timestamp.abs_value)
2631       break; /* ACK does not match our original CONNECT message */
2632     n->state = S_CONNECTED;
2633     n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2634     GNUNET_STATISTICS_set (GST_stats, 
2635                            gettext_noop ("# peers connected"), 
2636                            ++neighbours_connected,
2637                            GNUNET_NO);
2638     connect_notify_cb (callback_cls, &n->id, ats, ats_count,
2639                        n->primary_address.bandwidth_in,
2640                        n->primary_address.bandwidth_out);
2641     /* Tell ATS that the outbound session we created to send CONNECT was successfull */
2642     GNUNET_ATS_address_add (GST_ats,
2643                             n->primary_address.address,
2644                             n->primary_address.session,
2645                             ats, ats_count);
2646     set_address (&n->primary_address,
2647                  n->primary_address.address,
2648                  n->primary_address.session,
2649                  n->primary_address.bandwidth_in,
2650                  n->primary_address.bandwidth_out,
2651                  GNUNET_YES);
2652     send_session_ack_message (n);
2653     break;
2654   case S_CONNECT_RECV_BLACKLIST_INBOUND:
2655   case S_CONNECT_RECV_ATS:
2656   case S_CONNECT_RECV_BLACKLIST:
2657   case S_CONNECT_RECV_ACK:
2658     GNUNET_STATISTICS_update (GST_stats,
2659                               gettext_noop
2660                               ("# unexpected CONNECT_ACK messages (not ready)"),
2661                               1, GNUNET_NO);
2662     break;
2663   case S_CONNECTED:
2664     /* duplicate CONNECT_ACK, let's answer by duplciate SESSION_ACK just in case */
2665     send_session_ack_message (n);
2666     break;
2667   case S_RECONNECT_ATS:
2668   case S_RECONNECT_BLACKLIST:
2669     /* we didn't expect any CONNECT_ACK, as we are waiting for ATS
2670        to give us a new address... */
2671     GNUNET_STATISTICS_update (GST_stats,
2672                               gettext_noop
2673                               ("# unexpected CONNECT_ACK messages (waiting on ATS)"),
2674                               1, GNUNET_NO);
2675     break;
2676   case S_RECONNECT_SENT:
2677     /* new address worked; go back to connected! */
2678     n->state = S_CONNECTED;
2679     send_session_ack_message (n);
2680     break;
2681   case S_CONNECTED_SWITCHING_BLACKLIST:
2682     /* duplicate CONNECT_ACK, let's answer by duplciate SESSION_ACK just in case */
2683     send_session_ack_message (n);
2684     break;
2685   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2686     /* new address worked; adopt it and go back to connected! */
2687     n->state = S_CONNECTED;
2688     n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2689     GNUNET_break (GNUNET_NO == n->alternative_address.ats_active);
2690     GNUNET_ATS_address_add(GST_ats,
2691                            n->alternative_address.address,
2692                            n->alternative_address.session,
2693                            ats, ats_count);
2694     set_address (&n->primary_address,
2695                  n->alternative_address.address,
2696                  n->alternative_address.session,
2697                  n->alternative_address.bandwidth_in,
2698                  n->alternative_address.bandwidth_out,
2699                  GNUNET_YES);
2700     free_address (&n->alternative_address);
2701     send_session_ack_message (n);
2702     break;    
2703   case S_DISCONNECT:
2704     GNUNET_STATISTICS_update (GST_stats,
2705                               gettext_noop
2706                               ("# unexpected CONNECT_ACK messages (disconnecting)"),
2707                               1, GNUNET_NO);
2708     break;
2709   case S_DISCONNECT_FINISHED:
2710     GNUNET_assert (0);
2711     break;
2712   default:
2713     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2714     GNUNET_break (0);
2715     break;   
2716   }
2717 }
2718
2719
2720 /**
2721  * A session was terminated. Take note; if needed, try to get
2722  * an alternative address from ATS.
2723  *
2724  * @param peer identity of the peer where the session died
2725  * @param session session that is gone
2726  * @return GNUNET_YES if this was a session used, GNUNET_NO if
2727  *        this session was not in use
2728  */
2729 int
2730 GST_neighbours_session_terminated (const struct GNUNET_PeerIdentity *peer,
2731                                    struct Session *session)
2732 {
2733   struct NeighbourMapEntry *n;
2734   struct BlackListCheckContext *bcc;
2735   struct BlackListCheckContext *bcc_next;
2736
2737   /* make sure to cancel all ongoing blacklist checks involving 'session' */
2738   bcc_next = bc_head;
2739   while (NULL != (bcc = bcc_next))
2740   {
2741     bcc_next = bcc->next;
2742     if (bcc->na.session == session)
2743     {
2744       GST_blacklist_test_cancel (bcc->bc);
2745       GNUNET_HELLO_address_free (bcc->na.address);
2746       GNUNET_CONTAINER_DLL_remove (bc_head,
2747                                    bc_tail,
2748                                    bcc);
2749       GNUNET_free (bcc);
2750     }
2751   }
2752   if (NULL == (n = lookup_neighbour (peer)))
2753     return GNUNET_NO; /* can't affect us */
2754   if (session != n->primary_address.session)
2755   {
2756     if (session == n->alternative_address.session)
2757     {
2758       free_address (&n->alternative_address);
2759       if ( (S_CONNECTED_SWITCHING_BLACKLIST == n->state) ||
2760            (S_CONNECTED_SWITCHING_CONNECT_SENT == n->state) )
2761         n->state = S_CONNECTED;
2762       else
2763         GNUNET_break (0);
2764     }
2765     return GNUNET_NO; /* doesn't affect us further */
2766   }
2767
2768   n->expect_latency_response = GNUNET_NO;
2769   switch (n->state)
2770   {
2771   case S_NOT_CONNECTED:
2772     GNUNET_break (0);
2773     free_neighbour (n, GNUNET_NO);
2774     return GNUNET_YES;
2775   case S_INIT_ATS:
2776     GNUNET_break (0);
2777     free_neighbour (n, GNUNET_NO);
2778     return GNUNET_YES;
2779   case S_INIT_BLACKLIST:
2780   case S_CONNECT_SENT:
2781     free_address (&n->primary_address);
2782     n->state = S_INIT_ATS;
2783     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
2784     // FIXME: need to ask ATS for suggestions again?
2785     GNUNET_ATS_suggest_address (GST_ats, &n->id);
2786     break;
2787   case S_CONNECT_RECV_BLACKLIST_INBOUND:
2788   case S_CONNECT_RECV_ATS:    
2789   case S_CONNECT_RECV_BLACKLIST:
2790   case S_CONNECT_RECV_ACK:
2791     /* error on inbound session; free neighbour entirely */
2792     free_address (&n->primary_address);
2793     free_neighbour (n, GNUNET_NO);
2794     return GNUNET_YES;
2795   case S_CONNECTED:
2796     free_address (&n->primary_address);
2797     n->state = S_RECONNECT_ATS;
2798     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
2799     /* FIXME: is this ATS call needed? */
2800     GNUNET_ATS_suggest_address (GST_ats, &n->id);
2801     break;
2802   case S_RECONNECT_ATS:
2803     /* we don't have an address, how can it go down? */
2804     GNUNET_break (0);
2805     break;
2806   case S_RECONNECT_BLACKLIST:
2807   case S_RECONNECT_SENT:
2808     n->state = S_RECONNECT_ATS;
2809     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
2810     // FIXME: need to ask ATS for suggestions again?
2811     GNUNET_ATS_suggest_address (GST_ats, &n->id);
2812     break;
2813   case S_CONNECTED_SWITCHING_BLACKLIST:
2814     /* primary went down while we were checking secondary against
2815        blacklist, adopt secondary as primary */       
2816     free_address (&n->primary_address);
2817     n->primary_address = n->alternative_address;
2818     memset (&n->alternative_address, 0, sizeof (struct NeighbourAddress));
2819     n->timeout = GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT);
2820     n->state = S_RECONNECT_BLACKLIST;
2821     break;
2822   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2823     /* primary went down while we were waiting for CONNECT_ACK on secondary;
2824        secondary as primary */       
2825     free_address (&n->primary_address);
2826     n->primary_address = n->alternative_address;
2827     memset (&n->alternative_address, 0, sizeof (struct NeighbourAddress));
2828     n->timeout = GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT);
2829     n->state = S_RECONNECT_SENT;
2830     break;
2831   case S_DISCONNECT:
2832     free_address (&n->primary_address);
2833     break;
2834   case S_DISCONNECT_FINISHED:
2835     /* neighbour was freed and plugins told to terminate session */
2836     return GNUNET_NO;
2837     break;
2838   default:
2839     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2840     GNUNET_break (0);
2841     break;
2842   }
2843   if (GNUNET_SCHEDULER_NO_TASK != n->task)
2844     GNUNET_SCHEDULER_cancel (n->task);
2845   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
2846   return GNUNET_YES;
2847 }
2848
2849
2850 /**
2851  * We received a 'SESSION_ACK' message from the other peer.
2852  * If we sent a 'CONNECT_ACK' last, this means we are now
2853  * connected.  Otherwise, do nothing.
2854  *
2855  * @param message possibly a 'struct SessionConnectMessage' (check format)
2856  * @param peer identity of the peer to switch the address for
2857  * @param address address of the other peer, NULL if other peer
2858  *                       connected to us
2859  * @param session session to use (or NULL)
2860  * @param ats performance data
2861  * @param ats_count number of entries in ats
2862  */
2863 void
2864 GST_neighbours_handle_session_ack (const struct GNUNET_MessageHeader *message,
2865                                    const struct GNUNET_PeerIdentity *peer,
2866                                    const struct GNUNET_HELLO_Address *address,
2867                                    struct Session *session,
2868                                    const struct GNUNET_ATS_Information *ats,
2869                                    uint32_t ats_count)
2870 {
2871   struct NeighbourMapEntry *n;
2872
2873   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
2874               "Received SESSION_ACK message from peer `%s'\n",
2875               GNUNET_i2s (peer));
2876   if (ntohs (message->size) != sizeof (struct GNUNET_MessageHeader))
2877   {
2878     GNUNET_break_op (0);
2879     return;
2880   }
2881   if (NULL == (n = lookup_neighbour (peer)))
2882     return;
2883   /* check if we are in a plausible state for having sent
2884      a CONNECT_ACK.  If not, return, otherwise break */
2885   if ( ( (S_CONNECT_RECV_ACK != n->state) &&
2886          (S_CONNECT_SENT != n->state) ) ||
2887        (2 != n->send_connect_ack) )
2888   {
2889     GNUNET_STATISTICS_update (GST_stats,
2890                               gettext_noop ("# unexpected SESSION ACK messages"), 1,
2891                               GNUNET_NO);
2892     return;
2893   }
2894   n->state = S_CONNECTED;
2895   n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2896   GNUNET_STATISTICS_set (GST_stats, 
2897                          gettext_noop ("# peers connected"), 
2898                          ++neighbours_connected,
2899                          GNUNET_NO);
2900   connect_notify_cb (callback_cls, &n->id, ats, ats_count,
2901                      n->primary_address.bandwidth_in,
2902                      n->primary_address.bandwidth_out);
2903   GNUNET_ATS_address_add(GST_ats,
2904                          n->primary_address.address,
2905                          n->primary_address.session,
2906                          ats, ats_count);
2907   set_address (&n->primary_address,
2908                n->primary_address.address,
2909                n->primary_address.session,
2910                n->primary_address.bandwidth_in,
2911                n->primary_address.bandwidth_out,
2912                GNUNET_YES);
2913 }
2914
2915
2916 /**
2917  * Test if we're connected to the given peer.
2918  *
2919  * @param target peer to test
2920  * @return GNUNET_YES if we are connected, GNUNET_NO if not
2921  */
2922 int
2923 GST_neighbours_test_connected (const struct GNUNET_PeerIdentity *target)
2924 {
2925   return test_connected (lookup_neighbour (target));
2926 }
2927
2928
2929 /**
2930  * Change the incoming quota for the given peer.
2931  *
2932  * @param neighbour identity of peer to change qutoa for
2933  * @param quota new quota
2934  */
2935 void
2936 GST_neighbours_set_incoming_quota (const struct GNUNET_PeerIdentity *neighbour,
2937                                    struct GNUNET_BANDWIDTH_Value32NBO quota)
2938 {
2939   struct NeighbourMapEntry *n;
2940
2941   if (NULL == (n = lookup_neighbour (neighbour)))
2942   {
2943     GNUNET_STATISTICS_update (GST_stats,
2944                               gettext_noop
2945                               ("# SET QUOTA messages ignored (no such peer)"),
2946                               1, GNUNET_NO);
2947     return;
2948   }
2949   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2950               "Setting inbound quota of %u Bps for peer `%s' to all clients\n",
2951               ntohl (quota.value__), GNUNET_i2s (&n->id));
2952   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker, quota);
2953   if (0 != ntohl (quota.value__))
2954     return;
2955   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting peer `%4s' due to `%s'\n",
2956               GNUNET_i2s (&n->id), "SET_QUOTA");
2957   if (GNUNET_YES == test_connected (n))
2958     GNUNET_STATISTICS_update (GST_stats,
2959                               gettext_noop ("# disconnects due to quota of 0"),
2960                               1, GNUNET_NO);
2961   disconnect_neighbour (n);
2962 }
2963
2964
2965 /**
2966  * We received a disconnect message from the given peer,
2967  * validate and process.
2968  *
2969  * @param peer sender of the message
2970  * @param msg the disconnect message
2971  */
2972 void
2973 GST_neighbours_handle_disconnect_message (const struct GNUNET_PeerIdentity
2974                                           *peer,
2975                                           const struct GNUNET_MessageHeader
2976                                           *msg)
2977 {
2978   struct NeighbourMapEntry *n;
2979   const struct SessionDisconnectMessage *sdm;
2980   struct GNUNET_HashCode hc;
2981
2982   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2983               "Received DISCONNECT message from peer `%s'\n",
2984               GNUNET_i2s (peer));
2985   if (ntohs (msg->size) != sizeof (struct SessionDisconnectMessage))
2986   {
2987     // GNUNET_break_op (0);
2988     GNUNET_STATISTICS_update (GST_stats,
2989                               gettext_noop
2990                               ("# disconnect messages ignored (old format)"), 1,
2991                               GNUNET_NO);
2992     return;
2993   }
2994   sdm = (const struct SessionDisconnectMessage *) msg;
2995   if (NULL == (n = lookup_neighbour (peer)))
2996     return;                     /* gone already */
2997   if (GNUNET_TIME_absolute_ntoh (sdm->timestamp).abs_value <= n->connect_ack_timestamp.abs_value)
2998   {
2999     GNUNET_STATISTICS_update (GST_stats,
3000                               gettext_noop
3001                               ("# disconnect messages ignored (timestamp)"), 1,
3002                               GNUNET_NO);
3003     return;
3004   }
3005   GNUNET_CRYPTO_hash (&sdm->public_key,
3006                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3007                       &hc);
3008   if (0 != memcmp (peer, &hc, sizeof (struct GNUNET_PeerIdentity)))
3009   {
3010     GNUNET_break_op (0);
3011     return;
3012   }
3013   if (ntohl (sdm->purpose.size) !=
3014       sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
3015       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
3016       sizeof (struct GNUNET_TIME_AbsoluteNBO))
3017   {
3018     GNUNET_break_op (0);
3019     return;
3020   }
3021   if (GNUNET_OK !=
3022       GNUNET_CRYPTO_rsa_verify
3023       (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT, &sdm->purpose,
3024        &sdm->signature, &sdm->public_key))
3025   {
3026     GNUNET_break_op (0);
3027     return;
3028   }
3029   if (GNUNET_YES == test_connected (n))
3030     GNUNET_STATISTICS_update (GST_stats,
3031                               gettext_noop
3032                               ("# other peer asked to disconnect from us"), 1,
3033                               GNUNET_NO);
3034   disconnect_neighbour (n);
3035 }
3036
3037
3038 /**
3039  * Closure for the neighbours_iterate function.
3040  */
3041 struct IteratorContext
3042 {
3043   /**
3044    * Function to call on each connected neighbour.
3045    */
3046   GST_NeighbourIterator cb;
3047
3048   /**
3049    * Closure for 'cb'.
3050    */
3051   void *cb_cls;
3052 };
3053
3054
3055 /**
3056  * Call the callback from the closure for each connected neighbour.
3057  *
3058  * @param cls the 'struct IteratorContext'
3059  * @param key the hash of the public key of the neighbour
3060  * @param value the 'struct NeighbourMapEntry'
3061  * @return GNUNET_OK (continue to iterate)
3062  */
3063 static int
3064 neighbours_iterate (void *cls, const struct GNUNET_HashCode * key, void *value)
3065 {
3066   struct IteratorContext *ic = cls;
3067   struct NeighbourMapEntry *n = value;
3068
3069   if (GNUNET_YES == test_connected (n))
3070   {
3071     struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in;
3072     struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out;
3073
3074     if (NULL != n->primary_address.address)
3075     {
3076       bandwidth_in = n->primary_address.bandwidth_in;
3077       bandwidth_out = n->primary_address.bandwidth_out;
3078     }
3079     else
3080     {
3081       bandwidth_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
3082       bandwidth_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
3083     }
3084
3085     ic->cb (ic->cb_cls, &n->id, NULL, 0,
3086             n->primary_address.address,
3087             bandwidth_in, bandwidth_out);
3088   }
3089   return GNUNET_OK;
3090 }
3091
3092
3093 /**
3094  * Iterate over all connected neighbours.
3095  *
3096  * @param cb function to call
3097  * @param cb_cls closure for cb
3098  */
3099 void
3100 GST_neighbours_iterate (GST_NeighbourIterator cb, void *cb_cls)
3101 {
3102   struct IteratorContext ic;
3103
3104   if (NULL == neighbours)  
3105     return; /* can happen during shutdown */
3106   ic.cb = cb;
3107   ic.cb_cls = cb_cls;
3108   GNUNET_CONTAINER_multihashmap_iterate (neighbours, &neighbours_iterate, &ic);
3109 }
3110
3111
3112 /**
3113  * If we have an active connection to the given target, it must be shutdown.
3114  *
3115  * @param target peer to disconnect from
3116  */
3117 void
3118 GST_neighbours_force_disconnect (const struct GNUNET_PeerIdentity *target)
3119 {
3120   struct NeighbourMapEntry *n;
3121
3122   if (NULL == (n = lookup_neighbour (target)))
3123     return;  /* not active */
3124   if (GNUNET_YES == test_connected (n))
3125     GNUNET_STATISTICS_update (GST_stats,
3126                               gettext_noop
3127                               ("# disconnected from peer upon explicit request"), 1,
3128                               GNUNET_NO);
3129   disconnect_neighbour (n);
3130 }
3131
3132
3133 /**
3134  * Obtain current latency information for the given neighbour.
3135  *
3136  * @param peer to get the latency for
3137  * @return observed latency of the address, FOREVER if the 
3138  *         the connection is not up
3139  */
3140 struct GNUNET_TIME_Relative
3141 GST_neighbour_get_latency (const struct GNUNET_PeerIdentity *peer)
3142 {
3143   struct NeighbourMapEntry *n;
3144
3145   n = lookup_neighbour (peer);
3146   if (NULL == n) 
3147     return GNUNET_TIME_UNIT_FOREVER_REL;
3148   switch (n->state)
3149   {
3150   case S_CONNECTED:
3151   case S_CONNECTED_SWITCHING_CONNECT_SENT:
3152   case S_CONNECTED_SWITCHING_BLACKLIST:
3153   case S_RECONNECT_SENT:
3154   case S_RECONNECT_ATS:
3155   case S_RECONNECT_BLACKLIST:
3156     return n->latency;
3157   case S_NOT_CONNECTED:
3158   case S_INIT_BLACKLIST:
3159   case S_INIT_ATS:
3160   case S_CONNECT_RECV_BLACKLIST_INBOUND:
3161   case S_CONNECT_RECV_ATS:
3162   case S_CONNECT_RECV_BLACKLIST:
3163   case S_CONNECT_RECV_ACK:
3164   case S_CONNECT_SENT:
3165   case S_DISCONNECT:
3166   case S_DISCONNECT_FINISHED:
3167     return GNUNET_TIME_UNIT_FOREVER_REL;
3168   default:
3169     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
3170     GNUNET_break (0);
3171     break;
3172   }
3173   return GNUNET_TIME_UNIT_FOREVER_REL;   
3174 }
3175
3176
3177 /**
3178  * Obtain current address information for the given neighbour.
3179  *
3180  * @param peer
3181  * @return address currently used
3182  */
3183 struct GNUNET_HELLO_Address *
3184 GST_neighbour_get_current_address (const struct GNUNET_PeerIdentity *peer)
3185 {
3186   struct NeighbourMapEntry *n;
3187
3188   n = lookup_neighbour (peer);
3189   if (NULL == n)
3190     return NULL;
3191   return n->primary_address.address;
3192 }
3193
3194
3195 /**
3196  * Initialize the neighbours subsystem.
3197  *
3198  * @param cls closure for callbacks
3199  * @param connect_cb function to call if we connect to a peer
3200  * @param disconnect_cb function to call if we disconnect from a peer
3201  * @param peer_address_cb function to call if we change an active address
3202  *                   of a neighbour
3203  */
3204 void
3205 GST_neighbours_start (void *cls,
3206     NotifyConnect connect_cb,
3207                       GNUNET_TRANSPORT_NotifyDisconnect disconnect_cb,
3208                       GNUNET_TRANSPORT_PeerIterateCallback peer_address_cb)
3209 {
3210   callback_cls = cls;
3211   connect_notify_cb = connect_cb;
3212   disconnect_notify_cb = disconnect_cb;
3213   address_change_cb = peer_address_cb;
3214   neighbours = GNUNET_CONTAINER_multihashmap_create (NEIGHBOUR_TABLE_SIZE, GNUNET_NO);
3215 }
3216
3217
3218 /**
3219  * Disconnect from the given neighbour.
3220  *
3221  * @param cls unused
3222  * @param key hash of neighbour's public key (not used)
3223  * @param value the 'struct NeighbourMapEntry' of the neighbour
3224  * @return GNUNET_OK (continue to iterate)
3225  */
3226 static int
3227 disconnect_all_neighbours (void *cls, const struct GNUNET_HashCode * key, void *value)
3228 {
3229   struct NeighbourMapEntry *n = value;
3230
3231   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
3232               "Disconnecting peer `%4s', %s\n",
3233               GNUNET_i2s (&n->id), "SHUTDOWN_TASK");
3234   n->state = S_DISCONNECT_FINISHED;
3235   free_neighbour (n, GNUNET_NO);
3236   return GNUNET_OK;
3237 }
3238
3239
3240 /**
3241  * Cleanup the neighbours subsystem.
3242  */
3243 void
3244 GST_neighbours_stop ()
3245 {
3246   if (NULL == neighbours)
3247     return;
3248   GNUNET_CONTAINER_multihashmap_iterate (neighbours, 
3249                                          &disconnect_all_neighbours,
3250                                          NULL);
3251   GNUNET_CONTAINER_multihashmap_destroy (neighbours);
3252   neighbours = NULL;
3253   callback_cls = NULL;
3254   connect_notify_cb = NULL;
3255   disconnect_notify_cb = NULL;
3256   address_change_cb = NULL;
3257 }
3258
3259
3260 /* end of file gnunet-service-transport_neighbours.c */