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