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