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