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