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