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