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