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