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