-fixing compiler warnings on FreeBSD
[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   {
1132     GNUNET_free (mq);
1133     return; /* disconnect or other error while transmitting, can happen */
1134   }
1135   if (n->is_active == mq)
1136   {
1137     /* this is still "our" neighbour, remove us from its queue
1138        and allow it to send the next message now */
1139     n->is_active = NULL;
1140     if (GNUNET_SCHEDULER_NO_TASK != n->task)
1141       GNUNET_SCHEDULER_cancel (n->task);
1142     n->task = GNUNET_SCHEDULER_add_now (&master_task, n);    
1143   }
1144   GNUNET_assert (bytes_in_send_queue >= mq->message_buf_size);
1145   bytes_in_send_queue -= mq->message_buf_size;
1146   GNUNET_STATISTICS_set (GST_stats,
1147                         gettext_noop
1148                          ("# bytes in message queue for other peers"),
1149                          bytes_in_send_queue, GNUNET_NO);
1150   if (GNUNET_OK == success)
1151     GNUNET_STATISTICS_update (GST_stats,
1152                               gettext_noop
1153                               ("# messages transmitted to other peers"),
1154                               1, GNUNET_NO);
1155   else
1156     GNUNET_STATISTICS_update (GST_stats,
1157                               gettext_noop
1158                               ("# transmission failures for messages to other peers"),
1159                               1, GNUNET_NO);
1160   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1161               "Sending message to `%s' of type %u was a %s\n",
1162               GNUNET_i2s (receiver),
1163               ntohs (((struct GNUNET_MessageHeader *) mq->message_buf)->type),
1164               (success == GNUNET_OK) ? "success" : "FAILURE");
1165   if (NULL != mq->cont)
1166     mq->cont (mq->cont_cls, success);
1167   GNUNET_free (mq);
1168 }
1169
1170
1171 /**
1172  * Check the message list for the given neighbour and if we can
1173  * send a message, do so.  This function should only be called
1174  * if the connection is at least generally ready for transmission.
1175  * While we will only send one message at a time, no bandwidth
1176  * quota management is performed here.  If a message was given to
1177  * the plugin, the continuation will automatically re-schedule
1178  * the 'master' task once the next message might be transmitted.
1179  *
1180  * @param n target peer for which to transmit
1181  */
1182 static void
1183 try_transmission_to_peer (struct NeighbourMapEntry *n)
1184 {
1185   struct MessageQueue *mq;
1186   struct GNUNET_TIME_Relative timeout;
1187
1188   if (NULL == n->primary_address.address)
1189   {
1190     /* no address, why are we here? */
1191     GNUNET_break (0);
1192     return;
1193   }
1194   if ((0 == n->primary_address.address->address_length) && 
1195       (NULL == n->primary_address.session))
1196   {
1197     /* no address, why are we here? */
1198     GNUNET_break (0);
1199     return;
1200   }
1201   if (NULL != n->is_active)
1202   {
1203     /* transmission already pending */
1204     return;                     
1205   }
1206
1207   /* timeout messages from the queue that are past their due date */
1208   while (NULL != (mq = n->messages_head))
1209   {
1210     timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1211     if (timeout.rel_value > 0)
1212       break;
1213     GNUNET_STATISTICS_update (GST_stats,
1214                               gettext_noop
1215                               ("# messages timed out while in transport queue"),
1216                               1, GNUNET_NO);
1217     GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
1218     n->is_active = mq;
1219     transmit_send_continuation (mq, &n->id, GNUNET_SYSERR);     /* timeout */
1220   }
1221   if (NULL == mq)
1222     return;                     /* no more messages */
1223   GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
1224   n->is_active = mq;
1225   send_with_session (n,
1226                      mq->message_buf, mq->message_buf_size,
1227                      0 /* priority */, timeout,
1228                      &transmit_send_continuation, mq);
1229 }
1230
1231
1232 /**
1233  * Send keepalive message to the neighbour.  Must only be called
1234  * if we are on 'connected' state.  Will internally determine
1235  * if a keepalive is truly needed (so can always be called).
1236  *
1237  * @param n neighbour that went idle and needs a keepalive
1238  */
1239 static void
1240 send_keepalive (struct NeighbourMapEntry *n)
1241 {
1242   struct GNUNET_MessageHeader m;
1243
1244   GNUNET_assert (S_CONNECTED == n->state);
1245   if (GNUNET_TIME_absolute_get_remaining (n->keep_alive_time).rel_value > 0)
1246     return; /* no keepalive needed at this time */
1247   m.size = htons (sizeof (struct GNUNET_MessageHeader));
1248   m.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE);
1249   send_with_session (n,
1250                      (const void *) &m, sizeof (m),
1251                      UINT32_MAX /* priority */,
1252                      KEEPALIVE_FREQUENCY,
1253                      NULL, NULL);
1254   GNUNET_STATISTICS_update (GST_stats, gettext_noop ("# keepalives sent"), 1,
1255                             GNUNET_NO);
1256   n->expect_latency_response = GNUNET_YES;
1257   n->last_keep_alive_time = GNUNET_TIME_absolute_get ();
1258   n->keep_alive_time = GNUNET_TIME_relative_to_absolute (KEEPALIVE_FREQUENCY);
1259 }
1260
1261
1262 /**
1263  * Keep the connection to the given neighbour alive longer,
1264  * we received a KEEPALIVE (or equivalent); send a response.
1265  *
1266  * @param neighbour neighbour to keep alive (by sending keep alive response)
1267  */
1268 void
1269 GST_neighbours_keepalive (const struct GNUNET_PeerIdentity *neighbour)
1270 {
1271   struct NeighbourMapEntry *n;
1272   struct GNUNET_MessageHeader m;
1273
1274   if (NULL == (n = lookup_neighbour (neighbour)))
1275   {
1276     GNUNET_STATISTICS_update (GST_stats,
1277                               gettext_noop
1278                               ("# KEEPALIVE messages discarded (peer unknown)"),
1279                               1, GNUNET_NO);
1280     return;
1281   }
1282   if (NULL == n->primary_address.session)
1283   {
1284     GNUNET_STATISTICS_update (GST_stats,
1285                               gettext_noop
1286                               ("# KEEPALIVE messages discarded (no session)"),
1287                               1, GNUNET_NO);
1288     return;
1289   }
1290   /* send reply to allow neighbour to measure latency */
1291   m.size = htons (sizeof (struct GNUNET_MessageHeader));
1292   m.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE_RESPONSE);
1293   send_with_session(n,
1294                     (const void *) &m, sizeof (m),
1295                     UINT32_MAX /* priority */,
1296                     KEEPALIVE_FREQUENCY,
1297                     NULL, NULL);
1298 }
1299
1300
1301 /**
1302  * We received a KEEP_ALIVE_RESPONSE message and use this to calculate
1303  * latency to this peer.  Pass the updated information (existing ats
1304  * plus calculated latency) to ATS.
1305  *
1306  * @param neighbour neighbour to keep alive
1307  * @param ats performance data
1308  * @param ats_count number of entries in ats
1309  */
1310 void
1311 GST_neighbours_keepalive_response (const struct GNUNET_PeerIdentity *neighbour,
1312                                    const struct GNUNET_ATS_Information *ats,
1313                                    uint32_t ats_count)
1314 {
1315   struct NeighbourMapEntry *n;
1316   uint32_t latency;
1317   struct GNUNET_ATS_Information ats_new[ats_count + 1];
1318
1319   if (NULL == (n = lookup_neighbour (neighbour)))
1320   {
1321     GNUNET_STATISTICS_update (GST_stats,
1322                               gettext_noop
1323                               ("# KEEPALIVE_RESPONSE messages discarded (not connected)"),
1324                               1, GNUNET_NO);
1325     return;
1326   }
1327   if ( (S_CONNECTED != n->state) ||
1328        (GNUNET_YES != n->expect_latency_response) )
1329   {
1330     GNUNET_STATISTICS_update (GST_stats,
1331                               gettext_noop
1332                               ("# KEEPALIVE_RESPONSE messages discarded (not expected)"),
1333                               1, GNUNET_NO);
1334     return;
1335   }
1336   n->expect_latency_response = GNUNET_NO;
1337   n->latency = GNUNET_TIME_absolute_get_duration (n->last_keep_alive_time);
1338   n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1339   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1340               "Latency for peer `%s' is %llu ms\n",
1341               GNUNET_i2s (&n->id), n->latency.rel_value);
1342   memcpy (ats_new, ats, sizeof (struct GNUNET_ATS_Information) * ats_count);
1343   /* append latency */
1344   ats_new[ats_count].type = htonl (GNUNET_ATS_QUALITY_NET_DELAY);
1345   if (n->latency.rel_value > UINT32_MAX)
1346     latency = UINT32_MAX;
1347   else
1348     latency = n->latency.rel_value;
1349   ats_new[ats_count].value = htonl (latency);
1350   GNUNET_ATS_address_update (GST_ats, 
1351                              n->primary_address.address, 
1352                              n->primary_address.session, ats_new,
1353                              ats_count + 1);
1354 }
1355
1356
1357 /**
1358  * We have received a message from the given sender.  How long should
1359  * we delay before receiving more?  (Also used to keep the peer marked
1360  * as live).
1361  *
1362  * @param sender sender of the message
1363  * @param size size of the message
1364  * @param do_forward set to GNUNET_YES if the message should be forwarded to clients
1365  *                   GNUNET_NO if the neighbour is not connected or violates the quota,
1366  *                   GNUNET_SYSERR if the connection is not fully up yet
1367  * @return how long to wait before reading more from this sender
1368  */
1369 struct GNUNET_TIME_Relative
1370 GST_neighbours_calculate_receive_delay (const struct GNUNET_PeerIdentity
1371                                         *sender, ssize_t size, int *do_forward)
1372 {
1373   struct NeighbourMapEntry *n;
1374   struct GNUNET_TIME_Relative ret;
1375   
1376   if (NULL == neighbours)
1377   {
1378     *do_forward = GNUNET_NO;
1379     return GNUNET_TIME_UNIT_FOREVER_REL; /* This can happen during shutdown */
1380   }
1381   if (NULL == (n = lookup_neighbour (sender)))
1382   {
1383     GST_neighbours_try_connect (sender);
1384     if (NULL == (n = lookup_neighbour (sender)))
1385     {
1386       GNUNET_STATISTICS_update (GST_stats,
1387                                 gettext_noop
1388                                 ("# messages discarded due to lack of neighbour record"),
1389                                 1, GNUNET_NO);
1390       *do_forward = GNUNET_NO;
1391       return GNUNET_TIME_UNIT_ZERO;
1392     }
1393   }
1394   if (! test_connected (n))
1395   {
1396     *do_forward = GNUNET_SYSERR;
1397     return GNUNET_TIME_UNIT_ZERO;
1398   }
1399   if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, size))
1400   {
1401     n->quota_violation_count++;
1402     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1403                 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
1404                 n->in_tracker.available_bytes_per_s__,
1405                 n->quota_violation_count);
1406     /* Discount 32k per violation */
1407     GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, -32 * 1024);
1408   }
1409   else
1410   {
1411     if (n->quota_violation_count > 0)
1412     {
1413       /* try to add 32k back */
1414       GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, 32 * 1024);
1415       n->quota_violation_count--;
1416     }
1417   }
1418   if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
1419   {
1420     GNUNET_STATISTICS_update (GST_stats,
1421                               gettext_noop
1422                               ("# bandwidth quota violations by other peers"),
1423                               1, GNUNET_NO);
1424     *do_forward = GNUNET_NO;
1425     return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
1426   }
1427   *do_forward = GNUNET_YES;
1428   ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 32 * 1024);
1429   if (ret.rel_value > 0)
1430   {
1431     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1432                 "Throttling read (%llu bytes excess at %u b/s), waiting %llu ms before reading more.\n",
1433                 (unsigned long long) n->in_tracker.
1434                 consumption_since_last_update__,
1435                 (unsigned int) n->in_tracker.available_bytes_per_s__,
1436                 (unsigned long long) ret.rel_value);
1437     GNUNET_STATISTICS_update (GST_stats,
1438                               gettext_noop ("# ms throttling suggested"),
1439                               (int64_t) ret.rel_value, GNUNET_NO);
1440   }
1441   return ret;
1442 }
1443
1444
1445 /**
1446  * Transmit a message to the given target using the active connection.
1447  *
1448  * @param target destination
1449  * @param msg message to send
1450  * @param msg_size number of bytes in msg
1451  * @param timeout when to fail with timeout
1452  * @param cont function to call when done
1453  * @param cont_cls closure for 'cont'
1454  */
1455 void
1456 GST_neighbours_send (const struct GNUNET_PeerIdentity *target, const void *msg,
1457                      size_t msg_size, struct GNUNET_TIME_Relative timeout,
1458                      GST_NeighbourSendContinuation cont, void *cont_cls)
1459 {
1460   struct NeighbourMapEntry *n;
1461   struct MessageQueue *mq;
1462
1463   /* All ove these cases should never happen; they are all API violations.
1464      But we check anyway, just to be sure. */
1465   if (NULL == (n = lookup_neighbour (target)))
1466   {
1467     GNUNET_break (0);
1468     if (NULL != cont)
1469       cont (cont_cls, GNUNET_SYSERR);
1470     return;
1471   }
1472   if (GNUNET_YES != test_connected (n))
1473   {
1474     GNUNET_break (0);
1475     if (NULL != cont)
1476       cont (cont_cls, GNUNET_SYSERR);
1477     return;
1478   }
1479   bytes_in_send_queue += msg_size;
1480   GNUNET_STATISTICS_set (GST_stats,
1481                          gettext_noop
1482                          ("# bytes in message queue for other peers"),
1483                          bytes_in_send_queue, GNUNET_NO);
1484   mq = GNUNET_malloc (sizeof (struct MessageQueue) + msg_size);
1485   mq->cont = cont;
1486   mq->cont_cls = cont_cls;
1487   memcpy (&mq[1], msg, msg_size);
1488   mq->message_buf = (const char *) &mq[1];
1489   mq->message_buf_size = msg_size;
1490   mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1491   GNUNET_CONTAINER_DLL_insert_tail (n->messages_head, n->messages_tail, mq);
1492   if ( (NULL != n->is_active) ||
1493        ( (NULL == n->primary_address.session) && (NULL == n->primary_address.address)) )
1494     return;
1495   if (GNUNET_SCHEDULER_NO_TASK != n->task)
1496     GNUNET_SCHEDULER_cancel (n->task);
1497   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
1498 }
1499
1500
1501 /**
1502  * Send a SESSION_CONNECT message via the given address.
1503  *
1504  * @param na address to use
1505  */
1506 static void
1507 send_session_connect (struct NeighbourAddress *na)
1508 {
1509   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1510   struct SessionConnectMessage connect_msg;
1511   
1512   if (NULL == (papi = GST_plugins_find (na->address->transport_name)))  
1513   {
1514     GNUNET_break (0);
1515     return;
1516   }
1517   if (NULL == na->session)
1518     na->session = papi->get_session (papi->cls, na->address);    
1519   if (NULL == na->session)
1520   {
1521     GNUNET_break (0);
1522     return;
1523   }
1524   na->connect_timestamp = GNUNET_TIME_absolute_get ();
1525   connect_msg.header.size = htons (sizeof (struct SessionConnectMessage));
1526   connect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT);
1527   connect_msg.reserved = htonl (0);
1528   connect_msg.timestamp = GNUNET_TIME_absolute_hton (na->connect_timestamp);
1529   (void) papi->send (papi->cls,
1530                      na->session,
1531                      (const char *) &connect_msg, sizeof (struct SessionConnectMessage),
1532                      UINT_MAX,
1533                      GNUNET_TIME_UNIT_FOREVER_REL,
1534                      NULL, NULL);
1535 }
1536
1537
1538 /**
1539  * Send a SESSION_CONNECT_ACK message via the given address.
1540  *
1541  * @param address address to use
1542  * @param session session to use
1543  * @param timestamp timestamp to use for the ACK message
1544  */
1545 static void
1546 send_session_connect_ack_message (const struct GNUNET_HELLO_Address *address,
1547                                   struct Session *session,
1548                                   struct GNUNET_TIME_Absolute timestamp)
1549 {
1550   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1551   struct SessionConnectMessage connect_msg;
1552   
1553   if (NULL == (papi = GST_plugins_find (address->transport_name)))  
1554   {
1555     GNUNET_break (0);
1556     return;
1557   }
1558   if (NULL == session)
1559     session = papi->get_session (papi->cls, address);    
1560   if (NULL == session)
1561   {
1562     GNUNET_break (0);
1563     return;
1564   }
1565   connect_msg.header.size = htons (sizeof (struct SessionConnectMessage));
1566   connect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT_ACK);
1567   connect_msg.reserved = htonl (0);
1568   connect_msg.timestamp = GNUNET_TIME_absolute_hton (timestamp);
1569   (void) papi->send (papi->cls,
1570                      session,
1571                      (const char *) &connect_msg, sizeof (struct SessionConnectMessage),
1572                      UINT_MAX,
1573                      GNUNET_TIME_UNIT_FOREVER_REL,
1574                      NULL, NULL);
1575 }
1576
1577
1578 /**
1579  * Create a fresh entry in the neighbour map for the given peer
1580  *
1581  * @param peer peer to create an entry for
1582  * @return new neighbour map entry
1583  */
1584 static struct NeighbourMapEntry *
1585 setup_neighbour (const struct GNUNET_PeerIdentity *peer)
1586 {
1587   struct NeighbourMapEntry *n;
1588
1589   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1590               "Creating new neighbour entry for `%s'\n", 
1591               GNUNET_i2s (peer));
1592   n = GNUNET_malloc (sizeof (struct NeighbourMapEntry));
1593   n->id = *peer;
1594   n->state = S_NOT_CONNECTED;
1595   n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
1596   GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
1597                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
1598                                  MAX_BANDWIDTH_CARRY_S);
1599   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
1600   GNUNET_assert (GNUNET_OK ==
1601                  GNUNET_CONTAINER_multihashmap_put (neighbours,
1602                                                     &n->id.hashPubKey, n,
1603                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1604   return n;
1605 }
1606
1607
1608 /**
1609  * Check if the two given addresses are the same.
1610  * Actually only checks if the sessions are non-NULL
1611  * (which they should be) and then if they are identical;
1612  * the actual addresses don't matter if the session
1613  * pointers match anyway, and we must have session pointers
1614  * at this time.
1615  *
1616  * @param a1 first address to compare
1617  * @param a2 other address to compare
1618  * @return GNUNET_NO if the addresses do not match, GNUNET_YES if they do match
1619  */
1620 static int
1621 address_matches (const struct NeighbourAddress *a1,
1622                  const struct NeighbourAddress *a2)
1623 {
1624   if ( (NULL == a1->session) ||
1625        (NULL == a2->session) )
1626   {
1627     GNUNET_break (0);
1628     return 0;
1629   }
1630   return (a1->session == a2->session) ? GNUNET_YES : GNUNET_NO;
1631 }
1632
1633
1634 /**
1635  * Try to create a connection to the given target (eventually).
1636  *
1637  * @param target peer to try to connect to
1638  */
1639 void
1640 GST_neighbours_try_connect (const struct GNUNET_PeerIdentity *target)
1641 {
1642   struct NeighbourMapEntry *n;
1643
1644   if (NULL == neighbours)  
1645     return; /* during shutdown, do nothing */
1646   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1647               "Asked to connect to peer `%s'\n",
1648               GNUNET_i2s (target));
1649   if (0 ==
1650       memcmp (target, &GST_my_identity, sizeof (struct GNUNET_PeerIdentity)))
1651   {
1652     /* refuse to connect to myself */
1653     /* FIXME: can this happen? Is this not an API violation? */
1654     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1655                 "Refusing to try to connect to myself.\n");
1656     return;
1657   }
1658   n = lookup_neighbour (target);
1659   if (NULL != n)
1660   {
1661     switch (n->state)
1662     {
1663     case S_NOT_CONNECTED:
1664       /* this should not be possible */
1665       GNUNET_break (0);
1666       free_neighbour (n, GNUNET_NO);
1667       break;
1668     case S_INIT_ATS:
1669     case S_INIT_BLACKLIST:
1670     case S_CONNECT_SENT:
1671     case S_CONNECT_RECV_ATS:
1672     case S_CONNECT_RECV_BLACKLIST:
1673     case S_CONNECT_RECV_ACK:
1674       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1675                   "Ignoring request to try to connect to `%s', already trying!\n",
1676                   GNUNET_i2s (target));
1677       return; /* already trying */
1678     case S_CONNECTED:      
1679     case S_RECONNECT_ATS:
1680     case S_RECONNECT_BLACKLIST:
1681     case S_RECONNECT_SENT:
1682     case S_CONNECTED_SWITCHING_BLACKLIST:
1683     case S_CONNECTED_SWITCHING_CONNECT_SENT:
1684       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1685                   "Ignoring request to try to connect, already connected to `%s'!\n",
1686                   GNUNET_i2s (target));
1687       return; /* already connected */
1688     case S_DISCONNECT:
1689       /* get rid of remains, ready to re-try immediately */
1690       free_neighbour (n, GNUNET_NO);
1691       break;
1692     case S_DISCONNECT_FINISHED:
1693       /* should not be possible */      
1694       GNUNET_assert (0); 
1695     default:
1696       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
1697       GNUNET_break (0);
1698       free_neighbour (n, GNUNET_NO);
1699       break;
1700     }
1701   }
1702   n = setup_neighbour (target);  
1703   n->state = S_INIT_ATS; 
1704   n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1705
1706   GNUNET_ATS_reset_backoff (GST_ats, target);
1707   GNUNET_ATS_suggest_address (GST_ats, target);
1708 }
1709
1710
1711 /**
1712  * Function called with the result of a blacklist check.
1713  *
1714  * @param cls closure with the 'struct BlackListCheckContext'
1715  * @param peer peer this check affects
1716  * @param result GNUNET_OK if the address is allowed
1717  */
1718 static void
1719 handle_test_blacklist_cont (void *cls,
1720                             const struct GNUNET_PeerIdentity *peer,
1721                             int result)
1722 {
1723   struct BlackListCheckContext *bcc = cls;
1724   struct NeighbourMapEntry *n;
1725
1726   bcc->bc = NULL;
1727   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1728               "Connection to new address of peer `%s' based on blacklist is `%s'\n",
1729               GNUNET_i2s (peer),
1730               (GNUNET_OK == result) ? "allowed" : "FORBIDDEN");
1731   if (GNUNET_OK == result)
1732   {
1733     /* valid new address, let ATS know! */
1734     GNUNET_ATS_address_update (GST_ats, 
1735                                bcc->na.address, 
1736                                bcc->na.session, 
1737                                bcc->ats, bcc->ats_count);
1738   }
1739   if (NULL == (n = lookup_neighbour (peer)))
1740     goto cleanup; /* nobody left to care about new address */
1741   switch (n->state)
1742   {
1743   case S_NOT_CONNECTED:
1744     /* this should not be possible */
1745     GNUNET_break (0);
1746     free_neighbour (n, GNUNET_NO);
1747     break;
1748   case S_INIT_ATS:
1749     /* still waiting on ATS suggestion */
1750     break;
1751   case S_INIT_BLACKLIST:
1752     /* check if the address the blacklist was fine with matches
1753        ATS suggestion, if so, we can move on! */
1754     if ( (GNUNET_OK == result) &&
1755          (1 == n->send_connect_ack) )
1756     {
1757       n->send_connect_ack = 2;
1758       send_session_connect_ack_message (bcc->na.address,
1759                                         bcc->na.session,
1760                                         n->connect_ack_timestamp);
1761     }
1762     if (GNUNET_YES != address_matches (&bcc->na, &n->primary_address))
1763       break; /* result for an address we currently don't care about */
1764     if (GNUNET_OK == result)
1765     {
1766       n->timeout = GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT);
1767       n->state = S_CONNECT_SENT;
1768       send_session_connect (&n->primary_address);
1769     }
1770     else
1771     {
1772       // FIXME: should also possibly destroy session with plugin!?
1773       GNUNET_ATS_address_destroyed (GST_ats,
1774                                     bcc->na.address,
1775                                     NULL);
1776       free_address (&n->primary_address);
1777       n->state = S_INIT_ATS;
1778       n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1779       // FIXME: do we need to ask ATS again for suggestions?
1780       GNUNET_ATS_suggest_address (GST_ats, &n->id);
1781     }
1782     break;
1783   case S_CONNECT_SENT:
1784     /* waiting on CONNECT_ACK, send ACK if one is pending */
1785     if ( (GNUNET_OK == result) &&
1786          (1 == n->send_connect_ack) )
1787     {
1788       n->send_connect_ack = 2;
1789       send_session_connect_ack_message (n->primary_address.address,
1790                                         n->primary_address.session,
1791                                         n->connect_ack_timestamp);
1792     }
1793     break; 
1794   case S_CONNECT_RECV_ATS:
1795     /* still waiting on ATS suggestion, don't care about blacklist */
1796     break; 
1797   case S_CONNECT_RECV_BLACKLIST:
1798     if (GNUNET_YES != address_matches (&bcc->na, &n->primary_address))
1799       break; /* result for an address we currently don't care about */
1800     if (GNUNET_OK == result)
1801     {
1802       n->timeout = GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT);
1803       n->state = S_CONNECT_RECV_ACK;
1804       send_session_connect_ack_message (bcc->na.address,
1805                                         bcc->na.session,
1806                                         n->connect_ack_timestamp);
1807       if (1 == n->send_connect_ack) 
1808         n->send_connect_ack = 2;
1809     }
1810     else
1811     {
1812       // FIXME: should also possibly destroy session with plugin!?
1813       GNUNET_ATS_address_destroyed (GST_ats,
1814                                     bcc->na.address,
1815                                     NULL);
1816       free_address (&n->primary_address);
1817       n->state = S_INIT_ATS;
1818       n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1819       // FIXME: do we need to ask ATS again for suggestions?
1820       GNUNET_ATS_reset_backoff (GST_ats, peer);
1821       GNUNET_ATS_suggest_address (GST_ats, &n->id);
1822     }
1823     break;
1824   case S_CONNECT_RECV_ACK:
1825     /* waiting on SESSION_ACK, send ACK if one is pending */
1826     if ( (GNUNET_OK == result) &&
1827          (1 == n->send_connect_ack) )
1828     {
1829       n->send_connect_ack = 2;
1830       send_session_connect_ack_message (n->primary_address.address,
1831                                         n->primary_address.session,
1832                                         n->connect_ack_timestamp);
1833     }
1834     break; 
1835   case S_CONNECTED:
1836     /* already connected, don't care about blacklist */
1837     break;
1838   case S_RECONNECT_ATS:
1839     /* still waiting on ATS suggestion, don't care about blacklist */
1840     break;     
1841   case S_RECONNECT_BLACKLIST:
1842     if ( (GNUNET_OK == result) &&
1843          (1 == n->send_connect_ack) )
1844     {
1845       n->send_connect_ack = 2;
1846       send_session_connect_ack_message (bcc->na.address,
1847                                         bcc->na.session,
1848                                         n->connect_ack_timestamp);
1849     }
1850     if (GNUNET_YES != address_matches (&bcc->na, &n->primary_address))
1851       break; /* result for an address we currently don't care about */
1852     if (GNUNET_OK == result)
1853     {
1854       send_session_connect (&n->primary_address);
1855       n->timeout = GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT);
1856       n->state = S_RECONNECT_SENT;
1857     }
1858     else
1859     {
1860       GNUNET_ATS_address_destroyed (GST_ats,
1861                                     bcc->na.address,
1862                                     NULL);
1863       n->state = S_RECONNECT_ATS;
1864       n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1865       // FIXME: do we need to ask ATS again for suggestions?
1866       GNUNET_ATS_suggest_address (GST_ats, &n->id);
1867     }
1868     break;
1869   case S_RECONNECT_SENT:
1870     /* waiting on CONNECT_ACK, don't care about blacklist */
1871     if ( (GNUNET_OK == result) &&
1872          (1 == n->send_connect_ack) )
1873     {
1874       n->send_connect_ack = 2;
1875       send_session_connect_ack_message (n->primary_address.address,
1876                                         n->primary_address.session,
1877                                         n->connect_ack_timestamp);
1878     }
1879     break;     
1880   case S_CONNECTED_SWITCHING_BLACKLIST:
1881     if (GNUNET_YES != address_matches (&bcc->na, &n->alternative_address))
1882       break; /* result for an address we currently don't care about */
1883     if (GNUNET_OK == result)
1884     {
1885       send_session_connect (&n->alternative_address);
1886       n->state = S_CONNECTED_SWITCHING_CONNECT_SENT;
1887     }
1888     else
1889     {
1890       GNUNET_ATS_address_destroyed (GST_ats,
1891                                     bcc->na.address,
1892                                     NULL);
1893       free_address (&n->alternative_address);
1894       n->state = S_CONNECTED;
1895     }
1896     break;
1897   case S_CONNECTED_SWITCHING_CONNECT_SENT:
1898     /* waiting on CONNECT_ACK, don't care about blacklist */
1899     if ( (GNUNET_OK == result) &&
1900          (1 == n->send_connect_ack) )
1901     {
1902       n->send_connect_ack = 2;
1903       send_session_connect_ack_message (n->primary_address.address,
1904                                         n->primary_address.session,
1905                                         n->connect_ack_timestamp);
1906     }
1907     break;     
1908   case S_DISCONNECT:
1909     /* Nothing to do here, ATS will already do what can be done */
1910     break;
1911   case S_DISCONNECT_FINISHED:
1912     /* should not be possible */
1913     GNUNET_assert (0);
1914     break;
1915   default:
1916     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
1917     GNUNET_break (0);
1918     free_neighbour (n, GNUNET_NO);
1919     break;
1920   }
1921  cleanup:
1922   GNUNET_HELLO_address_free (bcc->na.address);
1923   GNUNET_CONTAINER_DLL_remove (bc_head,
1924                                bc_tail,
1925                                bcc);
1926   GNUNET_free (bcc);
1927 }
1928
1929
1930 /**
1931  * We want to know if connecting to a particular peer via
1932  * a particular address is allowed.  Check it!
1933  *
1934  * @param peer identity of the peer to switch the address for
1935  * @param ts time at which the check was initiated
1936  * @param address address of the other peer, NULL if other peer
1937  *                       connected to us
1938  * @param session session to use (or NULL)
1939  * @param ats performance data
1940  * @param ats_count number of entries in ats (excluding 0-termination)
1941  */
1942 static void
1943 check_blacklist (const struct GNUNET_PeerIdentity *peer,
1944                  struct GNUNET_TIME_Absolute ts,
1945                  const struct GNUNET_HELLO_Address *address,
1946                  struct Session *session,
1947                  const struct GNUNET_ATS_Information *ats,
1948                  uint32_t ats_count)
1949 {
1950   struct BlackListCheckContext *bcc;
1951   struct GST_BlacklistCheck *bc;
1952
1953   bcc =
1954       GNUNET_malloc (sizeof (struct BlackListCheckContext) +
1955                      sizeof (struct GNUNET_ATS_Information) * ats_count);
1956   bcc->ats_count = ats_count;
1957   bcc->na.address = GNUNET_HELLO_address_copy (address);
1958   bcc->na.session = session;
1959   bcc->na.connect_timestamp = ts;
1960   bcc->ats = (struct GNUNET_ATS_Information *) &bcc[1];
1961   memcpy (bcc->ats, ats, sizeof (struct GNUNET_ATS_Information) * ats_count);
1962   GNUNET_CONTAINER_DLL_insert (bc_head,
1963                                bc_tail,
1964                                bcc);
1965   if (NULL != (bc = GST_blacklist_test_allowed (peer, 
1966                                                 address->transport_name,
1967                                                 &handle_test_blacklist_cont, bcc)))
1968     bcc->bc = bc; 
1969   /* if NULL == bc, 'cont' was already called and 'bcc' already free'd, so
1970      we must only store 'bc' if 'bc' is non-NULL... */
1971 }
1972
1973
1974 /**
1975  * We received a 'SESSION_CONNECT' message from the other peer.
1976  * Consider switching to it.
1977  *
1978  * @param message possibly a 'struct SessionConnectMessage' (check format)
1979  * @param peer identity of the peer to switch the address for
1980  * @param address address of the other peer, NULL if other peer
1981  *                       connected to us
1982  * @param session session to use (or NULL)
1983  * @param ats performance data
1984  * @param ats_count number of entries in ats (excluding 0-termination)
1985  */
1986 void
1987 GST_neighbours_handle_connect (const struct GNUNET_MessageHeader *message,
1988                                const struct GNUNET_PeerIdentity *peer,
1989                                const struct GNUNET_HELLO_Address *address,
1990                                struct Session *session,
1991                                const struct GNUNET_ATS_Information *ats,
1992                                uint32_t ats_count)
1993 {
1994   const struct SessionConnectMessage *scm;
1995   struct NeighbourMapEntry *n;
1996   struct GNUNET_TIME_Absolute ts;
1997
1998   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1999               "Received CONNECT message from peer `%s'\n", 
2000               GNUNET_i2s (peer));
2001   if (ntohs (message->size) != sizeof (struct SessionConnectMessage))
2002   {
2003     GNUNET_break_op (0);
2004     return;
2005   }
2006   if (NULL == neighbours)
2007     return; /* we're shutting down */
2008   scm = (const struct SessionConnectMessage *) message;
2009   GNUNET_break_op (0 == ntohl (scm->reserved));
2010   ts = GNUNET_TIME_absolute_ntoh (scm->timestamp);
2011   n = lookup_neighbour (peer);
2012   if (NULL == n)
2013     n = setup_neighbour (peer);
2014   n->send_connect_ack = 1;
2015   n->connect_ack_timestamp = ts;
2016   switch (n->state)
2017   {  
2018   case S_NOT_CONNECTED:
2019     n->state = S_CONNECT_RECV_ATS;
2020     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
2021     GNUNET_ATS_reset_backoff (GST_ats, peer);
2022     GNUNET_ATS_suggest_address (GST_ats, peer);
2023     check_blacklist (peer, ts, address, session, ats, ats_count);
2024     break;
2025   case S_INIT_ATS:
2026   case S_INIT_BLACKLIST:
2027   case S_CONNECT_SENT:
2028   case S_CONNECT_RECV_ATS:
2029   case S_CONNECT_RECV_BLACKLIST:
2030   case S_CONNECT_RECV_ACK:
2031     /* It can never hurt to have an alternative address in the above cases, 
2032        see if it is allowed */
2033     check_blacklist (peer, ts, address, session, ats, ats_count);
2034     break;
2035   case S_CONNECTED:
2036     /* we are already connected and can thus send the ACK immediately;
2037        still, it can never hurt to have an alternative address, so also
2038        tell ATS  about it */
2039     GNUNET_assert (NULL != n->primary_address.address);
2040     GNUNET_assert (NULL != n->primary_address.session);
2041     n->send_connect_ack = 0;
2042     send_session_connect_ack_message (n->primary_address.address,
2043                                       n->primary_address.session, ts);
2044     check_blacklist (peer, ts, address, session, ats, ats_count);
2045     break;
2046   case S_RECONNECT_ATS:
2047   case S_RECONNECT_BLACKLIST:
2048   case S_RECONNECT_SENT:
2049     /* It can never hurt to have an alternative address in the above cases, 
2050        see if it is allowed */
2051     check_blacklist (peer, ts, address, session, ats, ats_count);
2052     break;
2053   case S_CONNECTED_SWITCHING_BLACKLIST:
2054   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2055     /* we are already connected and can thus send the ACK immediately;
2056        still, it can never hurt to have an alternative address, so also
2057        tell ATS  about it */
2058     GNUNET_assert (NULL != n->primary_address.address);
2059     GNUNET_assert (NULL != n->primary_address.session);
2060     n->send_connect_ack = 0;
2061     send_session_connect_ack_message (n->primary_address.address,
2062                                       n->primary_address.session, ts);
2063     check_blacklist (peer, ts, address, session, ats, ats_count);
2064     break;
2065   case S_DISCONNECT:
2066     /* get rid of remains without terminating sessions, ready to re-try */
2067     free_neighbour (n, GNUNET_YES);
2068     n = setup_neighbour (peer);
2069     n->state = S_CONNECT_RECV_ATS;
2070     GNUNET_ATS_reset_backoff (GST_ats, peer);
2071     GNUNET_ATS_suggest_address (GST_ats, peer);
2072     break;
2073   case S_DISCONNECT_FINISHED:
2074     /* should not be possible */
2075     GNUNET_assert (0);
2076     break;
2077   default:
2078     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2079     GNUNET_break (0);
2080     free_neighbour (n, GNUNET_NO);
2081     break;
2082   }
2083 }
2084
2085
2086 /**
2087  * For an existing neighbour record, set the active connection to
2088  * use the given address.  
2089  *
2090  * @param peer identity of the peer to switch the address for
2091  * @param address address of the other peer, NULL if other peer
2092  *                       connected to us
2093  * @param session session to use (or NULL)
2094  * @param ats performance data
2095  * @param ats_count number of entries in ats
2096  * @param bandwidth_in inbound quota to be used when connection is up
2097  * @param bandwidth_out outbound quota to be used when connection is up
2098  */
2099 void
2100 GST_neighbours_switch_to_address (const struct GNUNET_PeerIdentity *peer,
2101                                   const struct GNUNET_HELLO_Address *address,
2102                                   struct Session *session,
2103                                   const struct GNUNET_ATS_Information *ats,
2104                                   uint32_t ats_count,
2105                                   struct GNUNET_BANDWIDTH_Value32NBO
2106                                   bandwidth_in,
2107                                   struct GNUNET_BANDWIDTH_Value32NBO
2108                                   bandwidth_out)
2109 {
2110   struct NeighbourMapEntry *n;
2111   struct GNUNET_TRANSPORT_PluginFunctions *papi;
2112
2113   GNUNET_assert (address->transport_name != NULL);
2114   if (NULL == (n = lookup_neighbour (peer)))
2115     return;
2116
2117   /* Obtain an session for this address from plugin */
2118   if (NULL == (papi = GST_plugins_find (address->transport_name)))
2119   {
2120     /* we don't have the plugin for this address */
2121     GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
2122     return;
2123   }
2124   if ((NULL == session) && (0 == address->address_length))
2125   {
2126     GNUNET_break (0);
2127     if (strlen (address->transport_name) > 0)
2128       GNUNET_ATS_address_destroyed (GST_ats, address, session);
2129     return;
2130   }
2131   if (NULL == session)
2132     session = papi->get_session (papi->cls, address);
2133   if (NULL == session)
2134   {
2135     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2136                 "Failed to obtain new session for peer `%s' and  address '%s'\n",
2137                 GNUNET_i2s (&address->peer), GST_plugins_a2s (address));    
2138     GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
2139     return;
2140   }
2141   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2142               "ATS tells us to switch to address '%s' for peer `%s'\n",
2143               (address->address_length != 0) ? GST_plugins_a2s (address): "<inbound>",
2144               GNUNET_i2s (peer));
2145   switch (n->state)
2146   {
2147   case S_NOT_CONNECTED:
2148     GNUNET_break (0);
2149     free_neighbour (n, GNUNET_NO);
2150     return;
2151   case S_INIT_ATS:
2152     set_address (&n->primary_address,
2153                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2154     n->state = S_INIT_BLACKLIST;
2155     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2156     check_blacklist (&n->id,
2157                      n->connect_ack_timestamp,
2158                      address, session, ats, ats_count);    
2159     break;
2160   case S_INIT_BLACKLIST:
2161     /* ATS suggests a different address, switch again */
2162     set_address (&n->primary_address,
2163                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2164     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2165     check_blacklist (&n->id,
2166                      n->connect_ack_timestamp,
2167                      address, session, ats, ats_count);    
2168     break;
2169   case S_CONNECT_SENT:
2170     /* ATS suggests a different address, switch again */
2171     set_address (&n->primary_address,
2172                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2173     n->state = S_INIT_BLACKLIST;
2174     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2175     check_blacklist (&n->id,
2176                      n->connect_ack_timestamp,
2177                      address, session, ats, ats_count);    
2178     break;
2179   case S_CONNECT_RECV_ATS:
2180     set_address (&n->primary_address,
2181                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2182     n->state = S_CONNECT_RECV_BLACKLIST;
2183     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2184     check_blacklist (&n->id,
2185                      n->connect_ack_timestamp,
2186                      address, session, ats, ats_count);    
2187     break;
2188   case S_CONNECT_RECV_BLACKLIST:
2189   case S_CONNECT_RECV_ACK:
2190     /* ATS asks us to switch while we were trying to connect; switch to new
2191        address and check blacklist again */
2192     set_address (&n->primary_address,
2193                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2194     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2195     check_blacklist (&n->id,
2196                      n->connect_ack_timestamp,
2197                      address, session, ats, ats_count);    
2198     break;
2199   case S_CONNECTED:
2200     GNUNET_assert (NULL != n->primary_address.address);
2201     GNUNET_assert (NULL != n->primary_address.session);
2202     if (n->primary_address.session == session)
2203     {
2204       /* not an address change, just a quota change */
2205       set_address (&n->primary_address,
2206                    address, session, bandwidth_in, bandwidth_out, GNUNET_YES);
2207       break;
2208     }
2209     /* ATS asks us to switch a life connection; see if we can get
2210        a CONNECT_ACK on it before we actually do this! */
2211     set_address (&n->alternative_address,
2212                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2213     n->state = S_CONNECTED_SWITCHING_BLACKLIST;
2214     check_blacklist (&n->id,
2215                      GNUNET_TIME_absolute_get (),
2216                      address, session, ats, ats_count);
2217     break;
2218   case S_RECONNECT_ATS:
2219     set_address (&n->primary_address,
2220                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2221     n->state = S_RECONNECT_BLACKLIST;
2222     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2223     check_blacklist (&n->id,
2224                      n->connect_ack_timestamp,
2225                      address, session, ats, ats_count);    
2226     break;
2227   case S_RECONNECT_BLACKLIST:
2228     /* ATS asks us to switch while we were trying to reconnect; switch to new
2229        address and check blacklist again */
2230     set_address (&n->primary_address,
2231                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2232     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2233     check_blacklist (&n->id,
2234                      n->connect_ack_timestamp,
2235                      address, session, ats, ats_count);    
2236     break;
2237   case S_RECONNECT_SENT:
2238     /* ATS asks us to switch while we were trying to reconnect; switch to new
2239        address and check blacklist again */
2240     set_address (&n->primary_address,
2241                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2242     n->state = S_RECONNECT_BLACKLIST;
2243     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2244     check_blacklist (&n->id,
2245                      n->connect_ack_timestamp,
2246                      address, session, ats, ats_count); 
2247     break;
2248   case S_CONNECTED_SWITCHING_BLACKLIST:
2249     if (n->primary_address.session == session)
2250     {
2251       /* ATS switches back to still-active session */
2252       free_address (&n->alternative_address);
2253       n->state = S_CONNECTED;
2254       break;
2255     }
2256     /* ATS asks us to switch a life connection, update blacklist check */
2257     set_address (&n->alternative_address,
2258                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2259     check_blacklist (&n->id,
2260                      GNUNET_TIME_absolute_get (),
2261                      address, session, ats, ats_count);
2262     break;
2263   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2264     if (n->primary_address.session == session)
2265     {
2266       /* ATS switches back to still-active session */
2267       free_address (&n->alternative_address);
2268       n->state = S_CONNECTED;
2269       break;
2270     }
2271     /* ATS asks us to switch a life connection, update blacklist check */
2272     set_address (&n->alternative_address,
2273                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2274     n->state = S_CONNECTED_SWITCHING_BLACKLIST;
2275     check_blacklist (&n->id,
2276                      GNUNET_TIME_absolute_get (),
2277                      address, session, ats, ats_count);
2278     break;
2279   case S_DISCONNECT:
2280     /* not going to switch addresses while disconnecting */
2281     return;
2282   case S_DISCONNECT_FINISHED:
2283     GNUNET_assert (0);
2284     break;
2285   default:
2286     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2287     GNUNET_break (0);
2288     break;
2289   }
2290 }
2291
2292
2293 /**
2294  * Master task run for every neighbour.  Performs all of the time-related
2295  * activities (keep alive, send next message, disconnect if idle, finish
2296  * clean up after disconnect).
2297  *
2298  * @param cls the 'struct NeighbourMapEntry' for which we are running
2299  * @param tc scheduler context (unused)
2300  */
2301 static void
2302 master_task (void *cls,
2303              const struct GNUNET_SCHEDULER_TaskContext *tc)
2304 {
2305   struct NeighbourMapEntry *n = cls;
2306   struct GNUNET_TIME_Relative delay;
2307
2308   n->task = GNUNET_SCHEDULER_NO_TASK;
2309   delay = GNUNET_TIME_absolute_get_remaining (n->timeout);  
2310   switch (n->state)
2311   {
2312   case S_NOT_CONNECTED:
2313     /* invalid state for master task, clean up */
2314     GNUNET_break (0);
2315     n->state = S_DISCONNECT_FINISHED;
2316     free_neighbour (n, GNUNET_NO);
2317     return;
2318   case S_INIT_ATS:
2319     if (0 == delay.rel_value)
2320     {
2321       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2322                   "Connection to `%s' timed out waiting for ATS to provide address\n",
2323                   GNUNET_i2s (&n->id));
2324       n->state = S_DISCONNECT_FINISHED;
2325       free_neighbour (n, GNUNET_NO);
2326       return;
2327     }
2328     break;
2329   case S_INIT_BLACKLIST:
2330     if (0 == delay.rel_value)
2331     {
2332       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2333                   "Connection to `%s' timed out waiting for BLACKLIST to approve address\n",
2334                   GNUNET_i2s (&n->id));
2335       n->state = S_DISCONNECT_FINISHED;
2336       free_neighbour (n, GNUNET_NO);
2337       return;
2338     }
2339     break;
2340   case S_CONNECT_SENT:
2341     if (0 == delay.rel_value)
2342     {
2343       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2344                   "Connection to `%s' timed out waiting for other peer to send CONNECT_ACK\n",
2345                   GNUNET_i2s (&n->id));
2346       disconnect_neighbour (n);
2347       return;
2348     }
2349     break;
2350   case S_CONNECT_RECV_ATS:
2351     if (0 == delay.rel_value)
2352     {
2353       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2354                   "Connection to `%s' timed out waiting ATS to provide address to use for CONNECT_ACK\n",
2355                   GNUNET_i2s (&n->id));
2356       n->state = S_DISCONNECT_FINISHED;
2357       free_neighbour (n, GNUNET_NO);
2358       return;
2359     }
2360     break;
2361   case S_CONNECT_RECV_BLACKLIST:
2362     if (0 == delay.rel_value)
2363     {
2364       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2365                   "Connection to `%s' timed out waiting BLACKLIST to approve address to use for CONNECT_ACK\n",
2366                   GNUNET_i2s (&n->id));
2367       n->state = S_DISCONNECT_FINISHED;
2368       free_neighbour (n, GNUNET_NO);
2369       return;
2370     }
2371     break;
2372   case S_CONNECT_RECV_ACK:
2373     if (0 == delay.rel_value)
2374     {
2375       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2376                   "Connection to `%s' timed out waiting for other peer to send SESSION_ACK\n",
2377                   GNUNET_i2s (&n->id));
2378       disconnect_neighbour (n);
2379       return;
2380     }
2381     break;
2382   case S_CONNECTED:
2383     if (0 == delay.rel_value)
2384     {
2385       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2386                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs\n",
2387                   GNUNET_i2s (&n->id));
2388       disconnect_neighbour (n);
2389       return;
2390     }
2391     try_transmission_to_peer (n);
2392     send_keepalive (n);
2393     break;
2394   case S_RECONNECT_ATS:
2395     if (0 == delay.rel_value)
2396     {
2397       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2398                   "Connection to `%s' timed out, waiting for ATS replacement address\n",
2399                   GNUNET_i2s (&n->id));
2400       disconnect_neighbour (n);
2401       return;
2402     }
2403     break;
2404   case S_RECONNECT_BLACKLIST:
2405     if (0 == delay.rel_value)
2406     {
2407       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2408                   "Connection to `%s' timed out, waiting for BLACKLIST to approve replacement address\n",
2409                   GNUNET_i2s (&n->id));
2410       disconnect_neighbour (n);
2411       return;
2412     }
2413     break;
2414   case S_RECONNECT_SENT:
2415     if (0 == delay.rel_value)
2416     {
2417       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2418                   "Connection to `%s' timed out, waiting for other peer to CONNECT_ACK replacement address\n",
2419                   GNUNET_i2s (&n->id));
2420       disconnect_neighbour (n);
2421       return;
2422     }
2423     break;
2424   case S_CONNECTED_SWITCHING_BLACKLIST:
2425     if (0 == delay.rel_value)
2426     {
2427       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2428                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs\n",
2429                   GNUNET_i2s (&n->id));
2430       disconnect_neighbour (n);
2431       return;
2432     }
2433     try_transmission_to_peer (n);
2434     send_keepalive (n);
2435     break;
2436   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2437     if (0 == delay.rel_value)
2438     {
2439       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2440                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs (after trying to CONNECT on alternative address)\n",
2441                   GNUNET_i2s (&n->id));
2442       disconnect_neighbour (n);
2443       return;
2444     }
2445     try_transmission_to_peer (n);
2446     send_keepalive (n);
2447     break;
2448   case S_DISCONNECT:
2449     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2450                 "Cleaning up connection to `%s' after sending DISCONNECT\n",
2451                 GNUNET_i2s (&n->id));
2452     n->state = S_DISCONNECT_FINISHED;
2453     free_neighbour (n, GNUNET_NO);
2454     return;
2455   case S_DISCONNECT_FINISHED:
2456     /* how did we get here!? */
2457     GNUNET_assert (0);
2458     break;
2459   default:
2460     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2461     GNUNET_break (0);
2462     break;  
2463   }
2464   delay = GNUNET_TIME_relative_min (GNUNET_TIME_absolute_get_remaining (n->keep_alive_time),
2465                                     delay);
2466   if (GNUNET_SCHEDULER_NO_TASK == n->task)
2467     n->task = GNUNET_SCHEDULER_add_delayed (delay,
2468                                             &master_task,
2469                                             n);
2470 }
2471
2472
2473 /**
2474  * Send a SESSION_ACK message to the neighbour to confirm that we
2475  * got his CONNECT_ACK.
2476  *
2477  * @param n neighbour to send the SESSION_ACK to
2478  */
2479 static void
2480 send_session_ack_message (struct NeighbourMapEntry *n)
2481 {
2482   struct GNUNET_MessageHeader msg;
2483
2484   msg.size = htons (sizeof (struct GNUNET_MessageHeader));
2485   msg.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_ACK);
2486   (void) send_with_session(n,
2487                            (const char *) &msg, sizeof (struct GNUNET_MessageHeader),
2488                            UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_REL,
2489                            NULL, NULL);
2490 }
2491
2492
2493 /**
2494  * We received a 'SESSION_CONNECT_ACK' message from the other peer.
2495  * Consider switching to it.
2496  *
2497  * @param message possibly a 'struct SessionConnectMessage' (check format)
2498  * @param peer identity of the peer to switch the address for
2499  * @param address address of the other peer, NULL if other peer
2500  *                       connected to us
2501  * @param session session to use (or NULL)
2502  * @param ats performance data
2503  * @param ats_count number of entries in ats
2504  */
2505 void
2506 GST_neighbours_handle_connect_ack (const struct GNUNET_MessageHeader *message,
2507                                    const struct GNUNET_PeerIdentity *peer,
2508                                    const struct GNUNET_HELLO_Address *address,
2509                                    struct Session *session,
2510                                    const struct GNUNET_ATS_Information *ats,
2511                                    uint32_t ats_count)
2512 {
2513   const struct SessionConnectMessage *scm;
2514   struct GNUNET_TIME_Absolute ts;
2515   struct NeighbourMapEntry *n;
2516
2517   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2518               "Received CONNECT_ACK message from peer `%s'\n",
2519               GNUNET_i2s (peer));
2520   if (ntohs (message->size) != sizeof (struct SessionConnectMessage))
2521   {
2522     GNUNET_break_op (0);
2523     return;
2524   }
2525   scm = (const struct SessionConnectMessage *) message;
2526   GNUNET_break_op (ntohl (scm->reserved) == 0);
2527   if (NULL == (n = lookup_neighbour (peer)))
2528   {
2529     GNUNET_STATISTICS_update (GST_stats,
2530                               gettext_noop
2531                               ("# unexpected CONNECT_ACK messages (no peer)"),
2532                               1, GNUNET_NO);
2533     return;
2534   }
2535   ts = GNUNET_TIME_absolute_ntoh (scm->timestamp);
2536   switch (n->state)
2537   {
2538   case S_NOT_CONNECTED:
2539     GNUNET_break (0);
2540     free_neighbour (n, GNUNET_NO);
2541     return;
2542   case S_INIT_ATS:
2543   case S_INIT_BLACKLIST:
2544     GNUNET_STATISTICS_update (GST_stats,
2545                               gettext_noop
2546                               ("# unexpected CONNECT_ACK messages (not ready)"),
2547                               1, GNUNET_NO);
2548     break;    
2549   case S_CONNECT_SENT:
2550     if (ts.abs_value != n->primary_address.connect_timestamp.abs_value)
2551       break; /* ACK does not match our original CONNECT message */
2552     n->state = S_CONNECTED;
2553     n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2554     GNUNET_STATISTICS_set (GST_stats, 
2555                            gettext_noop ("# peers connected"), 
2556                            ++neighbours_connected,
2557                            GNUNET_NO);
2558     connect_notify_cb (callback_cls, &n->id, ats, ats_count);
2559     set_address (&n->primary_address,
2560                  n->primary_address.address,
2561                  n->primary_address.session,
2562                  n->primary_address.bandwidth_in,
2563                  n->primary_address.bandwidth_out,
2564                  GNUNET_YES);
2565     send_session_ack_message (n);
2566     break;
2567   case S_CONNECT_RECV_ATS:
2568   case S_CONNECT_RECV_BLACKLIST:
2569   case S_CONNECT_RECV_ACK:
2570     GNUNET_STATISTICS_update (GST_stats,
2571                               gettext_noop
2572                               ("# unexpected CONNECT_ACK messages (not ready)"),
2573                               1, GNUNET_NO);
2574     break;
2575   case S_CONNECTED:
2576     /* duplicate CONNECT_ACK, let's answer by duplciate SESSION_ACK just in case */
2577     send_session_ack_message (n);
2578     break;
2579   case S_RECONNECT_ATS:
2580   case S_RECONNECT_BLACKLIST:
2581     /* we didn't expect any CONNECT_ACK, as we are waiting for ATS
2582        to give us a new address... */
2583     GNUNET_STATISTICS_update (GST_stats,
2584                               gettext_noop
2585                               ("# unexpected CONNECT_ACK messages (waiting on ATS)"),
2586                               1, GNUNET_NO);
2587     break;
2588   case S_RECONNECT_SENT:
2589     /* new address worked; go back to connected! */
2590     n->state = S_CONNECTED;
2591     send_session_ack_message (n);
2592     break;
2593   case S_CONNECTED_SWITCHING_BLACKLIST:
2594     /* duplicate CONNECT_ACK, let's answer by duplciate SESSION_ACK just in case */
2595     send_session_ack_message (n);
2596     break;
2597   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2598     /* new address worked; adopt it and go back to connected! */
2599     n->state = S_CONNECTED;
2600     n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2601     GNUNET_break (GNUNET_NO == n->alternative_address.ats_active);
2602     set_address (&n->primary_address,
2603                  n->alternative_address.address,
2604                  n->alternative_address.session,
2605                  n->alternative_address.bandwidth_in,
2606                  n->alternative_address.bandwidth_out,
2607                  GNUNET_YES);
2608     free_address (&n->alternative_address);
2609     send_session_ack_message (n);
2610     break;    
2611   case S_DISCONNECT:
2612     GNUNET_STATISTICS_update (GST_stats,
2613                               gettext_noop
2614                               ("# unexpected CONNECT_ACK messages (disconnecting)"),
2615                               1, GNUNET_NO);
2616     break;
2617   case S_DISCONNECT_FINISHED:
2618     GNUNET_assert (0);
2619     break;
2620   default:
2621     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2622     GNUNET_break (0);
2623     break;   
2624   }
2625 }
2626
2627
2628 /**
2629  * A session was terminated. Take note; if needed, try to get
2630  * an alternative address from ATS.
2631  *
2632  * @param peer identity of the peer where the session died
2633  * @param session session that is gone
2634  */
2635 void
2636 GST_neighbours_session_terminated (const struct GNUNET_PeerIdentity *peer,
2637                                    struct Session *session)
2638 {
2639   struct NeighbourMapEntry *n;
2640   struct BlackListCheckContext *bcc;
2641   struct BlackListCheckContext *bcc_next;
2642
2643   /* make sure to cancel all ongoing blacklist checks involving 'session' */
2644   bcc_next = bc_head;
2645   while (NULL != (bcc = bcc_next))
2646   {
2647     bcc_next = bcc->next;
2648     if (bcc->na.session == session)
2649     {
2650       GST_blacklist_test_cancel (bcc->bc);
2651       GNUNET_HELLO_address_free (bcc->na.address);
2652       GNUNET_CONTAINER_DLL_remove (bc_head,
2653                                    bc_tail,
2654                                    bcc);
2655       GNUNET_free (bcc);
2656     }
2657   }
2658   if (NULL == (n = lookup_neighbour (peer)))
2659     return; /* can't affect us */
2660   if (session != n->primary_address.session)
2661   {
2662     if (session == n->alternative_address.session)
2663     {
2664       free_address (&n->alternative_address);
2665       if ( (S_CONNECTED_SWITCHING_BLACKLIST == n->state) ||
2666            (S_CONNECTED_SWITCHING_CONNECT_SENT == n->state) )
2667         n->state = S_CONNECTED;
2668       else
2669         GNUNET_break (0);
2670     }
2671     return; /* doesn't affect us further */
2672   }
2673
2674   n->expect_latency_response = GNUNET_NO;
2675
2676   switch (n->state)
2677   {
2678   case S_NOT_CONNECTED:
2679     GNUNET_break (0);
2680     free_neighbour (n, GNUNET_NO);
2681     return;
2682   case S_INIT_ATS:
2683     GNUNET_break (0);
2684     free_neighbour (n, GNUNET_NO);
2685     return;
2686   case S_INIT_BLACKLIST:
2687   case S_CONNECT_SENT:
2688     free_address (&n->primary_address);
2689     n->state = S_INIT_ATS;
2690     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
2691     // FIXME: need to ask ATS for suggestions again?
2692     GNUNET_ATS_suggest_address (GST_ats, &n->id);
2693     break;
2694   case S_CONNECT_RECV_ATS:    
2695   case S_CONNECT_RECV_BLACKLIST:
2696   case S_CONNECT_RECV_ACK:
2697     /* error on inbound session; free neighbour entirely */
2698     free_address (&n->primary_address);
2699     free_neighbour (n, GNUNET_NO);
2700     return;
2701   case S_CONNECTED:
2702     free_address (&n->primary_address);
2703     n->state = S_RECONNECT_ATS;
2704     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
2705     /* FIXME: is this ATS call needed? */
2706     GNUNET_ATS_suggest_address (GST_ats, &n->id);
2707     break;
2708   case S_RECONNECT_ATS:
2709     /* we don't have an address, how can it go down? */
2710     GNUNET_break (0);
2711     break;
2712   case S_RECONNECT_BLACKLIST:
2713   case S_RECONNECT_SENT:
2714     n->state = S_RECONNECT_ATS;
2715     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
2716     // FIXME: need to ask ATS for suggestions again?
2717     GNUNET_ATS_suggest_address (GST_ats, &n->id);
2718     break;
2719   case S_CONNECTED_SWITCHING_BLACKLIST:
2720     /* primary went down while we were checking secondary against
2721        blacklist, adopt secondary as primary */       
2722     free_address (&n->primary_address);
2723     n->primary_address = n->alternative_address;
2724     memset (&n->alternative_address, 0, sizeof (struct NeighbourAddress));
2725     n->timeout = GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT);
2726     n->state = S_RECONNECT_BLACKLIST;
2727     break;
2728   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2729     /* primary went down while we were waiting for CONNECT_ACK on secondary;
2730        secondary as primary */       
2731     free_address (&n->primary_address);
2732     n->primary_address = n->alternative_address;
2733     memset (&n->alternative_address, 0, sizeof (struct NeighbourAddress));
2734     n->timeout = GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT);
2735     n->state = S_RECONNECT_SENT;
2736     break;
2737   case S_DISCONNECT:
2738     free_address (&n->primary_address);
2739     break;
2740   case S_DISCONNECT_FINISHED:
2741     /* neighbour was freed and plugins told to terminate session */
2742     break;
2743   default:
2744     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2745     GNUNET_break (0);
2746     break;
2747   }
2748   if (GNUNET_SCHEDULER_NO_TASK != n->task)
2749     GNUNET_SCHEDULER_cancel (n->task);
2750   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
2751 }
2752
2753
2754 /**
2755  * We received a 'SESSION_ACK' message from the other peer.
2756  * If we sent a 'CONNECT_ACK' last, this means we are now
2757  * connected.  Otherwise, do nothing.
2758  *
2759  * @param message possibly a 'struct SessionConnectMessage' (check format)
2760  * @param peer identity of the peer to switch the address for
2761  * @param address address of the other peer, NULL if other peer
2762  *                       connected to us
2763  * @param session session to use (or NULL)
2764  * @param ats performance data
2765  * @param ats_count number of entries in ats
2766  */
2767 void
2768 GST_neighbours_handle_session_ack (const struct GNUNET_MessageHeader *message,
2769                                    const struct GNUNET_PeerIdentity *peer,
2770                                    const struct GNUNET_HELLO_Address *address,
2771                                    struct Session *session,
2772                                    const struct GNUNET_ATS_Information *ats,
2773                                    uint32_t ats_count)
2774 {
2775   struct NeighbourMapEntry *n;
2776
2777   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
2778               "Received SESSION_ACK message from peer `%s'\n",
2779               GNUNET_i2s (peer));
2780   if (ntohs (message->size) != sizeof (struct GNUNET_MessageHeader))
2781   {
2782     GNUNET_break_op (0);
2783     return;
2784   }
2785   if (NULL == (n = lookup_neighbour (peer)))
2786     return;
2787   /* check if we are in a plausible state for having sent
2788      a CONNECT_ACK.  If not, return, otherwise break */
2789   if ( ( (S_CONNECT_RECV_ACK != n->state) &&
2790          (S_CONNECT_SENT != n->state) ) ||
2791        (2 != n->send_connect_ack) )
2792   {
2793     GNUNET_STATISTICS_update (GST_stats,
2794                               gettext_noop ("# unexpected SESSION ACK messages"), 1,
2795                               GNUNET_NO);
2796     return;
2797   }
2798   n->state = S_CONNECTED;
2799   n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2800   GNUNET_STATISTICS_set (GST_stats, 
2801                          gettext_noop ("# peers connected"), 
2802                          ++neighbours_connected,
2803                          GNUNET_NO);
2804   connect_notify_cb (callback_cls, &n->id, ats, ats_count);
2805   set_address (&n->primary_address,
2806                n->primary_address.address,
2807                n->primary_address.session,
2808                n->primary_address.bandwidth_in,
2809                n->primary_address.bandwidth_out,
2810                GNUNET_YES);
2811 }
2812
2813
2814 /**
2815  * Test if we're connected to the given peer.
2816  *
2817  * @param target peer to test
2818  * @return GNUNET_YES if we are connected, GNUNET_NO if not
2819  */
2820 int
2821 GST_neighbours_test_connected (const struct GNUNET_PeerIdentity *target)
2822 {
2823   return test_connected (lookup_neighbour (target));
2824 }
2825
2826
2827 /**
2828  * Change the incoming quota for the given peer.
2829  *
2830  * @param neighbour identity of peer to change qutoa for
2831  * @param quota new quota
2832  */
2833 void
2834 GST_neighbours_set_incoming_quota (const struct GNUNET_PeerIdentity *neighbour,
2835                                    struct GNUNET_BANDWIDTH_Value32NBO quota)
2836 {
2837   struct NeighbourMapEntry *n;
2838
2839   if (NULL == (n = lookup_neighbour (neighbour)))
2840   {
2841     GNUNET_STATISTICS_update (GST_stats,
2842                               gettext_noop
2843                               ("# SET QUOTA messages ignored (no such peer)"),
2844                               1, GNUNET_NO);
2845     return;
2846   }
2847   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2848               "Setting inbound quota of %u Bps for peer `%s' to all clients\n",
2849               ntohl (quota.value__), GNUNET_i2s (&n->id));
2850   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker, quota);
2851   if (0 != ntohl (quota.value__))
2852     return;
2853   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting peer `%4s' due to `%s'\n",
2854               GNUNET_i2s (&n->id), "SET_QUOTA");
2855   if (GNUNET_YES == test_connected (n))
2856     GNUNET_STATISTICS_update (GST_stats,
2857                               gettext_noop ("# disconnects due to quota of 0"),
2858                               1, GNUNET_NO);
2859   disconnect_neighbour (n);
2860 }
2861
2862
2863 /**
2864  * We received a disconnect message from the given peer,
2865  * validate and process.
2866  *
2867  * @param peer sender of the message
2868  * @param msg the disconnect message
2869  */
2870 void
2871 GST_neighbours_handle_disconnect_message (const struct GNUNET_PeerIdentity
2872                                           *peer,
2873                                           const struct GNUNET_MessageHeader
2874                                           *msg)
2875 {
2876   struct NeighbourMapEntry *n;
2877   const struct SessionDisconnectMessage *sdm;
2878   GNUNET_HashCode hc;
2879
2880   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2881               "Received DISCONNECT message from peer `%s'\n",
2882               GNUNET_i2s (peer));
2883   if (ntohs (msg->size) != sizeof (struct SessionDisconnectMessage))
2884   {
2885     // GNUNET_break_op (0);
2886     GNUNET_STATISTICS_update (GST_stats,
2887                               gettext_noop
2888                               ("# disconnect messages ignored (old format)"), 1,
2889                               GNUNET_NO);
2890     return;
2891   }
2892   sdm = (const struct SessionDisconnectMessage *) msg;
2893   if (NULL == (n = lookup_neighbour (peer)))
2894     return;                     /* gone already */
2895   if (GNUNET_TIME_absolute_ntoh (sdm->timestamp).abs_value <= n->connect_ack_timestamp.abs_value)
2896   {
2897     GNUNET_STATISTICS_update (GST_stats,
2898                               gettext_noop
2899                               ("# disconnect messages ignored (timestamp)"), 1,
2900                               GNUNET_NO);
2901     return;
2902   }
2903   GNUNET_CRYPTO_hash (&sdm->public_key,
2904                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2905                       &hc);
2906   if (0 != memcmp (peer, &hc, sizeof (struct GNUNET_PeerIdentity)))
2907   {
2908     GNUNET_break_op (0);
2909     return;
2910   }
2911   if (ntohl (sdm->purpose.size) !=
2912       sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2913       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
2914       sizeof (struct GNUNET_TIME_AbsoluteNBO))
2915   {
2916     GNUNET_break_op (0);
2917     return;
2918   }
2919   if (GNUNET_OK !=
2920       GNUNET_CRYPTO_rsa_verify
2921       (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT, &sdm->purpose,
2922        &sdm->signature, &sdm->public_key))
2923   {
2924     GNUNET_break_op (0);
2925     return;
2926   }
2927   if (GNUNET_YES == test_connected (n))
2928     GNUNET_STATISTICS_update (GST_stats,
2929                               gettext_noop
2930                               ("# other peer asked to disconnect from us"), 1,
2931                               GNUNET_NO);
2932   disconnect_neighbour (n);
2933 }
2934
2935
2936 /**
2937  * Closure for the neighbours_iterate function.
2938  */
2939 struct IteratorContext
2940 {
2941   /**
2942    * Function to call on each connected neighbour.
2943    */
2944   GST_NeighbourIterator cb;
2945
2946   /**
2947    * Closure for 'cb'.
2948    */
2949   void *cb_cls;
2950 };
2951
2952
2953 /**
2954  * Call the callback from the closure for each connected neighbour.
2955  *
2956  * @param cls the 'struct IteratorContext'
2957  * @param key the hash of the public key of the neighbour
2958  * @param value the 'struct NeighbourMapEntry'
2959  * @return GNUNET_OK (continue to iterate)
2960  */
2961 static int
2962 neighbours_iterate (void *cls, const GNUNET_HashCode * key, void *value)
2963 {
2964   struct IteratorContext *ic = cls;
2965   struct NeighbourMapEntry *n = value;
2966
2967   if (GNUNET_YES == test_connected (n))
2968     ic->cb (ic->cb_cls, &n->id, NULL, 0, n->primary_address.address);
2969   return GNUNET_OK;
2970 }
2971
2972
2973 /**
2974  * Iterate over all connected neighbours.
2975  *
2976  * @param cb function to call
2977  * @param cb_cls closure for cb
2978  */
2979 void
2980 GST_neighbours_iterate (GST_NeighbourIterator cb, void *cb_cls)
2981 {
2982   struct IteratorContext ic;
2983
2984   if (NULL == neighbours)  
2985     return; /* can happen during shutdown */
2986   ic.cb = cb;
2987   ic.cb_cls = cb_cls;
2988   GNUNET_CONTAINER_multihashmap_iterate (neighbours, &neighbours_iterate, &ic);
2989 }
2990
2991
2992 /**
2993  * If we have an active connection to the given target, it must be shutdown.
2994  *
2995  * @param target peer to disconnect from
2996  */
2997 void
2998 GST_neighbours_force_disconnect (const struct GNUNET_PeerIdentity *target)
2999 {
3000   struct NeighbourMapEntry *n;
3001
3002   if (NULL == (n = lookup_neighbour (target)))
3003     return;  /* not active */
3004   if (GNUNET_YES == test_connected (n))
3005     GNUNET_STATISTICS_update (GST_stats,
3006                               gettext_noop
3007                               ("# disconnected from peer upon explicit request"), 1,
3008                               GNUNET_NO);
3009   disconnect_neighbour (n);
3010 }
3011
3012
3013 /**
3014  * Obtain current latency information for the given neighbour.
3015  *
3016  * @param peer to get the latency for
3017  * @return observed latency of the address, FOREVER if the 
3018  *         the connection is not up
3019  */
3020 struct GNUNET_TIME_Relative
3021 GST_neighbour_get_latency (const struct GNUNET_PeerIdentity *peer)
3022 {
3023   struct NeighbourMapEntry *n;
3024
3025   n = lookup_neighbour (peer);
3026   if (NULL == n) 
3027     return GNUNET_TIME_UNIT_FOREVER_REL;
3028   switch (n->state)
3029   {
3030   case S_CONNECTED:
3031   case S_RECONNECT_SENT:
3032   case S_RECONNECT_ATS:
3033     return n->latency;
3034   case S_NOT_CONNECTED:
3035   case S_INIT_BLACKLIST:
3036   case S_INIT_ATS:
3037   case S_CONNECT_SENT:
3038   case S_CONNECT_RECV_BLACKLIST:
3039   case S_DISCONNECT:
3040   case S_DISCONNECT_FINISHED:
3041     return GNUNET_TIME_UNIT_FOREVER_REL;
3042   default:
3043     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
3044     GNUNET_break (0);
3045     break;
3046   }
3047   return GNUNET_TIME_UNIT_FOREVER_REL;   
3048 }
3049
3050
3051 /**
3052  * Obtain current address information for the given neighbour.
3053  *
3054  * @param peer
3055  * @return address currently used
3056  */
3057 struct GNUNET_HELLO_Address *
3058 GST_neighbour_get_current_address (const struct GNUNET_PeerIdentity *peer)
3059 {
3060   struct NeighbourMapEntry *n;
3061
3062   n = lookup_neighbour (peer);
3063   if (NULL == n)
3064     return NULL;
3065   return n->primary_address.address;
3066 }
3067
3068
3069 /**
3070  * Initialize the neighbours subsystem.
3071  *
3072  * @param cls closure for callbacks
3073  * @param connect_cb function to call if we connect to a peer
3074  * @param disconnect_cb function to call if we disconnect from a peer
3075  * @param peer_address_cb function to call if we change an active address
3076  *                   of a neighbour
3077  */
3078 void
3079 GST_neighbours_start (void *cls,
3080                       GNUNET_TRANSPORT_NotifyConnect connect_cb,
3081                       GNUNET_TRANSPORT_NotifyDisconnect disconnect_cb,
3082                       GNUNET_TRANSPORT_PeerIterateCallback peer_address_cb)
3083 {
3084   callback_cls = cls;
3085   connect_notify_cb = connect_cb;
3086   disconnect_notify_cb = disconnect_cb;
3087   address_change_cb = peer_address_cb;
3088   neighbours = GNUNET_CONTAINER_multihashmap_create (NEIGHBOUR_TABLE_SIZE);
3089 }
3090
3091
3092 /**
3093  * Disconnect from the given neighbour.
3094  *
3095  * @param cls unused
3096  * @param key hash of neighbour's public key (not used)
3097  * @param value the 'struct NeighbourMapEntry' of the neighbour
3098  * @return GNUNET_OK (continue to iterate)
3099  */
3100 static int
3101 disconnect_all_neighbours (void *cls, const GNUNET_HashCode * key, void *value)
3102 {
3103   struct NeighbourMapEntry *n = value;
3104
3105   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
3106               "Disconnecting peer `%4s', %s\n",
3107               GNUNET_i2s (&n->id), "SHUTDOWN_TASK");
3108   n->state = S_DISCONNECT_FINISHED;
3109   free_neighbour (n, GNUNET_NO);
3110   return GNUNET_OK;
3111 }
3112
3113
3114 /**
3115  * Cleanup the neighbours subsystem.
3116  */
3117 void
3118 GST_neighbours_stop ()
3119 {
3120   if (NULL == neighbours)
3121     return;
3122   GNUNET_CONTAINER_multihashmap_iterate (neighbours, 
3123                                          &disconnect_all_neighbours,
3124                                          NULL);
3125   GNUNET_CONTAINER_multihashmap_destroy (neighbours);
3126   neighbours = NULL;
3127   callback_cls = NULL;
3128   connect_notify_cb = NULL;
3129   disconnect_notify_cb = NULL;
3130   address_change_cb = NULL;
3131 }
3132
3133
3134 /* end of file gnunet-service-transport_neighbours.c */