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