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