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