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