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