refactoring how we handle peer addresses in peerinfo/ats/transport/hello subsystems...
[oweals/gnunet.git] / src / transport / gnunet-service-transport_neighbours.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010,2011 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 #include "platform.h"
27 #include "gnunet_ats_service.h"
28 #include "gnunet-service-transport_neighbours.h"
29 #include "gnunet-service-transport_plugins.h"
30 #include "gnunet-service-transport_validation.h"
31 #include "gnunet-service-transport_clients.h"
32 #include "gnunet-service-transport.h"
33 #include "gnunet_peerinfo_service.h"
34 #include "gnunet-service-transport_blacklist.h"
35 #include "gnunet_constants.h"
36 #include "transport.h"
37
38
39 /**
40  * Size of the neighbour hash map.
41  */
42 #define NEIGHBOUR_TABLE_SIZE 256
43
44 /**
45  * How often must a peer violate bandwidth quotas before we start
46  * to simply drop its messages?
47  */
48 #define QUOTA_VIOLATION_DROP_THRESHOLD 10
49
50 /**
51  * How often do we send KEEPALIVE messages to each of our neighbours?
52  * (idle timeout is 5 minutes or 300 seconds, so with 90s interval we
53  * send 3 keepalives in each interval, so 3 messages would need to be
54  * lost in a row for a disconnect).
55  */
56 #define KEEPALIVE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 90)
57
58
59 #define ATS_RESPONSE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 3)
60
61
62 #define SETUP_CONNECTION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
63
64
65 /**
66  * Entry in neighbours.
67  */
68 struct NeighbourMapEntry;
69
70 /**
71  * Message a peer sends to another to indicate its
72  * preference for communicating via a particular
73  * session (and the desire to establish a real
74  * connection).
75  */
76 struct SessionConnectMessage
77 {
78   /**
79    * Header of type 'GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT'
80    */
81   struct GNUNET_MessageHeader header;
82
83   /**
84    * Always zero.
85    */
86   uint32_t reserved GNUNET_PACKED;
87
88   /**
89    * Absolute time at the sender.  Only the most recent connect
90    * message implies which session is preferred by the sender.
91    */
92   struct GNUNET_TIME_AbsoluteNBO timestamp;
93
94 };
95
96
97 struct SessionDisconnectMessage
98 {
99   /**
100    * Header of type 'GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT'
101    */
102   struct GNUNET_MessageHeader header;
103
104   /**
105    * Always zero.
106    */
107   uint32_t reserved GNUNET_PACKED;
108
109   /**
110    * Purpose of the signature.  Extends over the timestamp.
111    * Purpose should be GNUNET_SIGNATURE_PURPOSE_TRANSPORT_DISCONNECT.
112    */
113   struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
114
115   /**
116    * Absolute time at the sender.  Only the most recent connect
117    * message implies which session is preferred by the sender.
118    */
119   struct GNUNET_TIME_AbsoluteNBO timestamp;
120
121   /**
122    * Public key of the sender.
123    */
124   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded public_key;
125
126   /**
127    * Signature of the peer that sends us the disconnect.  Only
128    * valid if the timestamp is AFTER the timestamp from the
129    * corresponding 'CONNECT' message.
130    */
131   struct GNUNET_CRYPTO_RsaSignature signature;
132
133 };
134
135
136 /**
137  * For each neighbour we keep a list of messages
138  * that we still want to transmit to the neighbour.
139  */
140 struct MessageQueue
141 {
142
143   /**
144    * This is a doubly linked list.
145    */
146   struct MessageQueue *next;
147
148   /**
149    * This is a doubly linked list.
150    */
151   struct MessageQueue *prev;
152
153   /**
154    * Once this message is actively being transmitted, which
155    * neighbour is it associated with?
156    */
157   struct NeighbourMapEntry *n;
158
159   /**
160    * Function to call once we're done.
161    */
162   GST_NeighbourSendContinuation cont;
163
164   /**
165    * Closure for 'cont'
166    */
167   void *cont_cls;
168
169   /**
170    * The message(s) we want to transmit, GNUNET_MessageHeader(s)
171    * stuck together in memory.  Allocated at the end of this struct.
172    */
173   const char *message_buf;
174
175   /**
176    * Size of the message buf
177    */
178   size_t message_buf_size;
179
180   /**
181    * At what time should we fail?
182    */
183   struct GNUNET_TIME_Absolute timeout;
184
185 };
186
187 enum State
188 {
189   /* fresh peer or completely disconnected */
190   S_NOT_CONNECTED = 0,
191   /* sent CONNECT message to other peer, waiting for CONNECT_ACK */
192   S_CONNECT_SENT = 1,
193   /* received CONNECT message to other peer, sending CONNECT_ACK */
194   S_CONNECT_RECV = 4,
195   /* sent CONNECT_ACK message to other peer, wait for ACK or payload */
196   S_CONNECT_RECV_ACK_SENT = 8,
197   /* received ACK or payload */
198   S_CONNECTED = 16,
199   /* Disconnect in progress */
200   S_DISCONNECT = 32
201 };
202
203 /**
204  * Entry in neighbours.
205  */
206 struct NeighbourMapEntry
207 {
208
209   /**
210    * Head of list of messages we would like to send to this peer;
211    * must contain at most one message per client.
212    */
213   struct MessageQueue *messages_head;
214
215   /**
216    * Tail of list of messages we would like to send to this peer; must
217    * contain at most one message per client.
218    */
219   struct MessageQueue *messages_tail;
220
221   /**
222    * Performance data for the peer.
223    */
224   //struct GNUNET_ATS_Information *ats;
225
226   /**
227    * Are we currently trying to send a message? If so, which one?
228    */
229   struct MessageQueue *is_active;
230
231   /**
232    * Active session for communicating with the peer.
233    */
234   struct Session *session;
235
236   /**
237    * Address we currently use.
238    */
239   struct GNUNET_HELLO_Address *address;
240
241   /**
242    * Identity of this neighbour.
243    */
244   struct GNUNET_PeerIdentity id;
245
246   /**
247    * ID of task scheduled to run when this peer is about to
248    * time out (will free resources associated with the peer).
249    */
250   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
251
252   /**
253    * ID of task scheduled to send keepalives.
254    */
255   GNUNET_SCHEDULER_TaskIdentifier keepalive_task;
256
257   /**
258    * ID of task scheduled to run when we should try transmitting
259    * the head of the message queue.
260    */
261   GNUNET_SCHEDULER_TaskIdentifier transmission_task;
262
263   /**
264    * Tracker for inbound bandwidth.
265    */
266   struct GNUNET_BANDWIDTH_Tracker in_tracker;
267
268   /**
269    * Inbound bandwidth from ATS, activated when connection is up
270    */
271   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in;
272
273   /**
274    * Inbound bandwidth from ATS, activated when connection is up
275    */
276   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out;
277
278   /**
279    * Timestamp of the 'SESSION_CONNECT' message we got from the other peer
280    */
281   struct GNUNET_TIME_Absolute connect_ts;
282
283   /**
284    * Timeout for ATS
285    * We asked ATS for a new address for this peer
286    */
287   GNUNET_SCHEDULER_TaskIdentifier ats_suggest;
288
289   /**
290    * Task the resets the peer state after due to an pending
291    * unsuccessful connection setup
292    */
293   GNUNET_SCHEDULER_TaskIdentifier state_reset;
294
295   /**
296    * How often has the other peer (recently) violated the inbound
297    * traffic limit?  Incremented by 10 per violation, decremented by 1
298    * per non-violation (for each time interval).
299    */
300   unsigned int quota_violation_count;
301
302
303   /**
304    * The current state of the peer
305    * Element of enum State
306    */
307   int state;
308
309 };
310
311
312 /**
313  * All known neighbours and their HELLOs.
314  */
315 static struct GNUNET_CONTAINER_MultiHashMap *neighbours;
316
317 /**
318  * Closure for connect_notify_cb and disconnect_notify_cb
319  */
320 static void *callback_cls;
321
322 /**
323  * Function to call when we connected to a neighbour.
324  */
325 static GNUNET_TRANSPORT_NotifyConnect connect_notify_cb;
326
327 /**
328  * Function to call when we disconnected from a neighbour.
329  */
330 static GNUNET_TRANSPORT_NotifyDisconnect disconnect_notify_cb;
331
332 /**
333  * counter for connected neighbours
334  */
335 static int neighbours_connected;
336
337 /**
338  * Lookup a neighbour entry in the neighbours hash map.
339  *
340  * @param pid identity of the peer to look up
341  * @return the entry, NULL if there is no existing record
342  */
343 static struct NeighbourMapEntry *
344 lookup_neighbour (const struct GNUNET_PeerIdentity *pid)
345 {
346   return GNUNET_CONTAINER_multihashmap_get (neighbours, &pid->hashPubKey);
347 }
348
349 #define change_state(n, state, ...) change (n, state, __LINE__)
350
351 static int
352 is_connecting (struct NeighbourMapEntry *n)
353 {
354   if ((n->state > S_NOT_CONNECTED) && (n->state < S_CONNECTED))
355     return GNUNET_YES;
356   return GNUNET_NO;
357 }
358
359 static int
360 is_connected (struct NeighbourMapEntry *n)
361 {
362   if (n->state == S_CONNECTED)
363     return GNUNET_YES;
364   return GNUNET_NO;
365 }
366
367 static int
368 is_disconnecting (struct NeighbourMapEntry *n)
369 {
370   if (n->state == S_DISCONNECT)
371     return GNUNET_YES;
372   return GNUNET_NO;
373 }
374
375 static const char *
376 print_state (int state)
377 {
378   switch (state)
379   {
380   case S_CONNECTED:
381     return "S_CONNECTED";
382     break;
383   case S_CONNECT_RECV:
384     return "S_CONNECT_RECV";
385     break;
386   case S_CONNECT_RECV_ACK_SENT:
387     return "S_CONNECT_RECV_ACK_SENT";
388     break;
389   case S_CONNECT_SENT:
390     return "S_CONNECT_SENT";
391     break;
392   case S_DISCONNECT:
393     return "S_DISCONNECT";
394     break;
395   case S_NOT_CONNECTED:
396     return "S_NOT_CONNECTED";
397     break;
398   default:
399     GNUNET_break (0);
400     break;
401   }
402   return NULL;
403 }
404
405 static int
406 change (struct NeighbourMapEntry *n, int state, int line);
407
408 static void
409 ats_suggest_cancel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
410
411 static void
412 reset_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
413 {
414   struct NeighbourMapEntry *n = cls;
415
416   n->state_reset = GNUNET_SCHEDULER_NO_TASK;
417
418 #if DEBUG_TRANSPORT
419 #endif
420   /* This jut a temporary debug message to check if a the value
421    * SETUP_CONNECTION_TIMEOUT was choosen to small for slow machines
422    */
423   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
424               "Information for developers: Connection to peer `%s' %s failed in state `%s', resetting connection attempt \n",
425               GNUNET_i2s (&n->id), GST_plugins_a2s (n->address),
426               print_state (n->state));
427
428   GNUNET_STATISTICS_update (GST_stats,
429                             gettext_noop
430                             ("# failed connection attempts due to timeout"), 1,
431                             GNUNET_NO);
432
433   /* resetting state */
434   n->state = S_NOT_CONNECTED;
435
436   /* destroying address */
437   GNUNET_ATS_address_destroyed (GST_ats, n->address, NULL);
438
439   /* request new address */
440   if (n->ats_suggest != GNUNET_SCHEDULER_NO_TASK)
441     GNUNET_SCHEDULER_cancel (n->ats_suggest);
442   n->ats_suggest =
443       GNUNET_SCHEDULER_add_delayed (ATS_RESPONSE_TIMEOUT, ats_suggest_cancel,
444                                     n);
445   GNUNET_ATS_suggest_address (GST_ats, &n->id);
446 }
447
448 static int
449 change (struct NeighbourMapEntry *n, int state, int line)
450 {
451   char *old = strdup (print_state (n->state));
452   char *new = strdup (print_state (state));
453
454   /* allowed transitions */
455   int allowed = GNUNET_NO;
456
457   switch (n->state)
458   {
459   case S_NOT_CONNECTED:
460     if ((state == S_CONNECT_RECV) || (state == S_CONNECT_SENT) ||
461         (state == S_DISCONNECT))
462     {
463       allowed = GNUNET_YES;
464
465       /* Schedule reset task */
466       if ((state == S_CONNECT_RECV) || (state == S_CONNECT_SENT))
467       {
468         GNUNET_assert (n->state_reset == GNUNET_SCHEDULER_NO_TASK);
469         n->state_reset =
470             GNUNET_SCHEDULER_add_delayed (SETUP_CONNECTION_TIMEOUT, &reset_task,
471                                           n);
472       }
473       break;
474     }
475     break;
476   case S_CONNECT_RECV:
477     if ((state == S_NOT_CONNECTED) || (state == S_DISCONNECT) ||
478         (state == S_CONNECTED) ||
479         /* FIXME SENT -> RECV ISSUE! */ (state == S_CONNECT_SENT))
480     {
481       if ((state == S_CONNECTED) || (state == S_DISCONNECT) ||
482           (state == S_NOT_CONNECTED))
483       {
484 #if DEBUG_TRANSPORT
485         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
486                     "Removed reset task for peer `%s' %s failed in state transition `%s' -> `%s' \n",
487                     GNUNET_i2s (&n->id), GST_plugins_a2s (n->address),
488                     print_state (n->state), print_state (state));
489 #endif
490         GNUNET_assert (n->state_reset != GNUNET_SCHEDULER_NO_TASK);
491         GNUNET_SCHEDULER_cancel (n->state_reset);
492         n->state_reset = GNUNET_SCHEDULER_NO_TASK;
493       }
494
495       allowed = GNUNET_YES;
496       break;
497     }
498     break;
499   case S_CONNECT_SENT:
500     if ((state == S_NOT_CONNECTED) || (state == S_CONNECTED) ||
501         (state == S_DISCONNECT) ||
502         /* FIXME SENT -> RECV ISSUE! */ (state == S_CONNECT_RECV))
503     {
504       if ((state == S_CONNECTED) || (state == S_DISCONNECT) ||
505           (state == S_NOT_CONNECTED))
506       {
507 #if DEBUG_TRANSPORT
508         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
509                     "Removed reset task for peer `%s' %s failed in state transition `%s' -> `%s' \n",
510                     GNUNET_i2s (&n->id), GST_plugins_a2s (n->address),
511                     print_state (n->state), print_state (state));
512 #endif
513         GNUNET_assert (n->state_reset != GNUNET_SCHEDULER_NO_TASK);
514         GNUNET_SCHEDULER_cancel (n->state_reset);
515         n->state_reset = GNUNET_SCHEDULER_NO_TASK;
516       }
517
518       allowed = GNUNET_YES;
519       break;
520     }
521     break;
522   case S_CONNECTED:
523     if (state == S_DISCONNECT)
524     {
525       allowed = GNUNET_YES;
526       break;
527     }
528     break;
529   case S_DISCONNECT:
530     /*
531      * if (state == S_NOT_CONNECTED)
532      * {
533      * allowed = GNUNET_YES;
534      * break;
535      * } */
536     break;
537   default:
538     GNUNET_break (0);
539     break;
540
541   }
542
543   if (allowed == GNUNET_NO)
544   {
545     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
546                 "Illegal state transition from `%s' to `%s' in line %u \n", old,
547                 new, line);
548     GNUNET_break (0);
549     GNUNET_free (old);
550     GNUNET_free (new);
551     return GNUNET_SYSERR;
552   }
553
554   n->state = state;
555 #if DEBUG_TRANSPORT
556   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
557               "State for neighbour `%s' %X changed from `%s' to `%s' in line %u\n",
558               GNUNET_i2s (&n->id), n, old, new, line);
559 #endif
560   GNUNET_free (old);
561   GNUNET_free (new);
562   return GNUNET_OK;
563 }
564
565 static ssize_t
566 send_with_plugin (const struct GNUNET_PeerIdentity *target, const char *msgbuf,
567                   size_t msgbuf_size, uint32_t priority,
568                   struct GNUNET_TIME_Relative timeout, struct Session *session,
569                   const struct GNUNET_HELLO_Address *address,
570                   int force_address, GNUNET_TRANSPORT_TransmitContinuation cont,
571                   void *cont_cls)
572 {
573   struct GNUNET_TRANSPORT_PluginFunctions *papi;
574   size_t ret = GNUNET_SYSERR;
575
576   /* FIXME : ats returns an address with all values 0 */
577   if (address == NULL)
578   {
579     if (cont != NULL)
580       cont (cont_cls, target, GNUNET_SYSERR);
581     return GNUNET_SYSERR;
582   }
583
584   if ((session == NULL) && (address == NULL))
585   {
586     if (cont != NULL)
587       cont (cont_cls, target, GNUNET_SYSERR);
588     return GNUNET_SYSERR;
589   }
590
591   papi = GST_plugins_find (address->transport_name);
592   if (papi == NULL)
593   {
594     if (cont != NULL)
595       cont (cont_cls, target, GNUNET_SYSERR);
596     return GNUNET_SYSERR;
597   }
598
599   ret =
600       papi->send (papi->cls, target, msgbuf, msgbuf_size, 0, timeout, session,
601                   address->address, 
602                   address->address_length, GNUNET_YES, cont, cont_cls);
603
604   if (ret == -1)
605   {
606     if (cont != NULL)
607       cont (cont_cls, target, GNUNET_SYSERR);
608   }
609   return ret;
610 }
611
612 /**
613  * Task invoked to start a transmission to another peer.
614  *
615  * @param cls the 'struct NeighbourMapEntry'
616  * @param tc scheduler context
617  */
618 static void
619 transmission_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
620
621
622 /**
623  * We're done with our transmission attempt, continue processing.
624  *
625  * @param cls the 'struct MessageQueue' of the message
626  * @param receiver intended receiver
627  * @param success whether it worked or not
628  */
629 static void
630 transmit_send_continuation (void *cls,
631                             const struct GNUNET_PeerIdentity *receiver,
632                             int success)
633 {
634   struct MessageQueue *mq;
635   struct NeighbourMapEntry *n;
636
637   mq = cls;
638   n = mq->n;
639   if (NULL != n)
640   {
641     GNUNET_assert (n->is_active == mq);
642     n->is_active = NULL;
643     if (success == GNUNET_YES)
644     {
645       GNUNET_assert (n->transmission_task == GNUNET_SCHEDULER_NO_TASK);
646       n->transmission_task = GNUNET_SCHEDULER_add_now (&transmission_task, n);
647     }
648   }
649 #if DEBUG_TRANSPORT
650   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending message of type %u was %s\n",
651               ntohs (((struct GNUNET_MessageHeader *) mq->message_buf)->type),
652               (success == GNUNET_OK) ? "successful" : "FAILED");
653 #endif
654   if (NULL != mq->cont)
655     mq->cont (mq->cont_cls, success);
656   GNUNET_free (mq);
657 }
658
659
660 /**
661  * Check the ready list for the given neighbour and if a plugin is
662  * ready for transmission (and if we have a message), do so!
663  *
664  * @param n target peer for which to transmit
665  */
666 static void
667 try_transmission_to_peer (struct NeighbourMapEntry *n)
668 {
669   struct MessageQueue *mq;
670   struct GNUNET_TIME_Relative timeout;
671   ssize_t ret;
672
673   if (n->is_active != NULL)
674   {
675     GNUNET_break (0);
676     return;                     /* transmission already pending */
677   }
678   if (n->transmission_task != GNUNET_SCHEDULER_NO_TASK)
679   {
680     GNUNET_break (0);
681     return;                     /* currently waiting for bandwidth */
682   }
683   while (NULL != (mq = n->messages_head))
684   {
685     timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
686     if (timeout.rel_value > 0)
687       break;
688     GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
689     n->is_active = mq;
690     mq->n = n;
691     transmit_send_continuation (mq, &n->id, GNUNET_SYSERR);     /* timeout */
692   }
693   if (NULL == mq)
694     return;                     /* no more messages */
695
696   if (GST_plugins_find (n->address->transport_name) == NULL)
697   {
698     GNUNET_break (0);
699     return;
700   }
701   GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
702   n->is_active = mq;
703   mq->n = n;
704
705   if ( (n->session == NULL) && (NULL == n->address) )
706   {
707     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
708                 "No address for peer `%s'\n",
709                 GNUNET_i2s (&n->id));
710     transmit_send_continuation (mq, &n->id, GNUNET_SYSERR);
711     GNUNET_assert (n->transmission_task == GNUNET_SCHEDULER_NO_TASK);
712     n->transmission_task = GNUNET_SCHEDULER_add_now (&transmission_task, n);
713     return;
714   }
715
716   ret =
717       send_with_plugin (&n->id, mq->message_buf, mq->message_buf_size, 0,
718                         timeout, n->session, n->address, 
719                         GNUNET_YES, &transmit_send_continuation,
720                         mq);
721   if (ret == -1)
722   {
723     /* failure, but 'send' would not call continuation in this case,
724      * so we need to do it here! */
725     transmit_send_continuation (mq, &n->id, GNUNET_SYSERR);
726   }
727
728 }
729
730
731 /**
732  * Task invoked to start a transmission to another peer.
733  *
734  * @param cls the 'struct NeighbourMapEntry'
735  * @param tc scheduler context
736  */
737 static void
738 transmission_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
739 {
740   struct NeighbourMapEntry *n = cls;
741
742   GNUNET_assert (NULL != lookup_neighbour (&n->id));
743   n->transmission_task = GNUNET_SCHEDULER_NO_TASK;
744   try_transmission_to_peer (n);
745 }
746
747
748 /**
749  * Initialize the neighbours subsystem.
750  *
751  * @param cls closure for callbacks
752  * @param connect_cb function to call if we connect to a peer
753  * @param disconnect_cb function to call if we disconnect from a peer
754  */
755 void
756 GST_neighbours_start (void *cls, GNUNET_TRANSPORT_NotifyConnect connect_cb,
757                       GNUNET_TRANSPORT_NotifyDisconnect disconnect_cb)
758 {
759   callback_cls = cls;
760   connect_notify_cb = connect_cb;
761   disconnect_notify_cb = disconnect_cb;
762   neighbours = GNUNET_CONTAINER_multihashmap_create (NEIGHBOUR_TABLE_SIZE);
763 }
764
765
766 static void
767 send_disconnect_cont (void *cls, const struct GNUNET_PeerIdentity *target,
768                       int result)
769 {
770 #if DEBUG_TRANSPORT
771   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
772               "Sending DISCONNECT message to peer `%4s': %i\n",
773               GNUNET_i2s (target), result);
774 #endif
775 }
776
777
778 static int
779 send_disconnect (const struct GNUNET_PeerIdentity *target,
780                  const struct GNUNET_HELLO_Address *address,
781                  struct Session *session)
782 {
783   size_t ret;
784   struct SessionDisconnectMessage disconnect_msg;
785
786 #if DEBUG_TRANSPORT
787   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
788               "Sending DISCONNECT message to peer `%4s'\n",
789               GNUNET_i2s (target));
790 #endif
791
792   disconnect_msg.header.size = htons (sizeof (struct SessionDisconnectMessage));
793   disconnect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
794   disconnect_msg.reserved = htonl (0);
795   disconnect_msg.purpose.size =
796       htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
797              sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
798              sizeof (struct GNUNET_TIME_AbsoluteNBO));
799   disconnect_msg.purpose.purpose =
800       htonl (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT);
801   disconnect_msg.timestamp =
802       GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
803   disconnect_msg.public_key = GST_my_public_key;
804   GNUNET_assert (GNUNET_OK ==
805                  GNUNET_CRYPTO_rsa_sign (GST_my_private_key,
806                                          &disconnect_msg.purpose,
807                                          &disconnect_msg.signature));
808
809   ret =
810       send_with_plugin (target, (const char *) &disconnect_msg,
811                         sizeof (disconnect_msg), UINT32_MAX,
812                         GNUNET_TIME_UNIT_FOREVER_REL, session, address,
813                         GNUNET_YES,
814                         &send_disconnect_cont, NULL);
815
816   if (ret == GNUNET_SYSERR)
817     return GNUNET_SYSERR;
818
819   GNUNET_STATISTICS_update (GST_stats,
820                             gettext_noop
821                             ("# peers disconnected due to external request"), 1,
822                             GNUNET_NO);
823   return GNUNET_OK;
824 }
825
826 /**
827  * Disconnect from the given neighbour, clean up the record.
828  *
829  * @param n neighbour to disconnect from
830  */
831 static void
832 disconnect_neighbour (struct NeighbourMapEntry *n)
833 {
834   struct MessageQueue *mq;
835   int was_connected = is_connected (n);
836
837   /* send DISCONNECT MESSAGE */
838   if (is_connected (n) || is_connecting (n))
839   {
840     if (GNUNET_OK ==
841         send_disconnect (&n->id, n->address,
842                          n->session))
843       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sent DISCONNECT_MSG to `%s'\n",
844                   GNUNET_i2s (&n->id));
845     else
846       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
847                   "Could not send DISCONNECT_MSG to `%s'\n",
848                   GNUNET_i2s (&n->id));
849   }
850
851   if (is_connected(n))
852   {
853      GNUNET_ATS_address_in_use (GST_ats, n->address, n->session, GNUNET_NO);
854   }
855
856
857   if (is_disconnecting (n))
858     return;
859   change_state (n, S_DISCONNECT);
860   GST_validation_set_address_use (&n->id,
861                                   n->address,
862                                   n->session,
863                                   GNUNET_NO);
864
865   if (n->address != NULL)
866   {
867     struct GNUNET_TRANSPORT_PluginFunctions *papi;
868     papi = GST_plugins_find (n->address->transport_name);
869     if (papi != NULL)
870       papi->disconnect (papi->cls, &n->id);
871   }
872
873   while (NULL != (mq = n->messages_head))
874   {
875     GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
876     if (NULL != mq->cont)
877       mq->cont (mq->cont_cls, GNUNET_SYSERR);
878     GNUNET_free (mq);
879   }
880   if (NULL != n->is_active)
881   {
882     n->is_active->n = NULL;
883     n->is_active = NULL;
884   }
885   if (was_connected)
886   {
887     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != n->keepalive_task);
888     GNUNET_SCHEDULER_cancel (n->keepalive_task);
889     n->keepalive_task = GNUNET_SCHEDULER_NO_TASK;
890     GNUNET_assert (neighbours_connected > 0);
891     neighbours_connected--;
892     GNUNET_STATISTICS_update (GST_stats, gettext_noop ("# peers connected"), -1,
893                               GNUNET_NO);
894     disconnect_notify_cb (callback_cls, &n->id);
895   }
896   GNUNET_assert (GNUNET_YES ==
897                  GNUNET_CONTAINER_multihashmap_remove (neighbours,
898                                                        &n->id.hashPubKey, n));
899   if (GNUNET_SCHEDULER_NO_TASK != n->ats_suggest)
900   {
901     GNUNET_SCHEDULER_cancel (n->ats_suggest);
902     n->ats_suggest = GNUNET_SCHEDULER_NO_TASK;
903   }
904   if (GNUNET_SCHEDULER_NO_TASK != n->timeout_task)
905   {
906     GNUNET_SCHEDULER_cancel (n->timeout_task);
907     n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
908   }
909   if (GNUNET_SCHEDULER_NO_TASK != n->transmission_task)
910   {
911     GNUNET_SCHEDULER_cancel (n->transmission_task);
912     n->transmission_task = GNUNET_SCHEDULER_NO_TASK;
913   }
914   if (NULL != n->address)
915   {
916     GNUNET_HELLO_address_free (n->address);
917     n->address = NULL;
918   }
919   n->session = NULL;
920   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Deleting peer `%4s', %X\n",
921               GNUNET_i2s (&n->id), n);
922   GNUNET_free (n);
923 }
924
925
926 /**
927  * Peer has been idle for too long. Disconnect.
928  *
929  * @param cls the 'struct NeighbourMapEntry' of the neighbour that went idle
930  * @param tc scheduler context
931  */
932 static void
933 neighbour_timeout_task (void *cls,
934                         const struct GNUNET_SCHEDULER_TaskContext *tc)
935 {
936   struct NeighbourMapEntry *n = cls;
937
938   n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
939
940   GNUNET_STATISTICS_update (GST_stats,
941                             gettext_noop
942                             ("# peers disconnected due to timeout"), 1,
943                             GNUNET_NO);
944   disconnect_neighbour (n);
945 }
946
947
948 /**
949  * Send another keepalive message.
950  *
951  * @param cls the 'struct NeighbourMapEntry' of the neighbour that went idle
952  * @param tc scheduler context
953  */
954 static void
955 neighbour_keepalive_task (void *cls,
956                           const struct GNUNET_SCHEDULER_TaskContext *tc)
957 {
958   struct NeighbourMapEntry *n = cls;
959   struct GNUNET_MessageHeader m;
960
961   n->keepalive_task =
962       GNUNET_SCHEDULER_add_delayed (KEEPALIVE_FREQUENCY,
963                                     &neighbour_keepalive_task, n);
964   GNUNET_assert (is_connected (n));
965   GNUNET_STATISTICS_update (GST_stats, gettext_noop ("# keepalives sent"), 1,
966                             GNUNET_NO);
967   m.size = htons (sizeof (struct GNUNET_MessageHeader));
968   m.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE);
969
970   send_with_plugin (&n->id, (const void *) &m, sizeof (m),
971                     UINT32_MAX /* priority */ ,
972                     GNUNET_TIME_UNIT_FOREVER_REL, n->session, n->address, 
973                     GNUNET_YES, NULL, NULL);
974 }
975
976
977 /**
978  * Disconnect from the given neighbour.
979  *
980  * @param cls unused
981  * @param key hash of neighbour's public key (not used)
982  * @param value the 'struct NeighbourMapEntry' of the neighbour
983  */
984 static int
985 disconnect_all_neighbours (void *cls, const GNUNET_HashCode * key, void *value)
986 {
987   struct NeighbourMapEntry *n = value;
988
989 #if DEBUG_TRANSPORT
990   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting peer `%4s', %s\n",
991               GNUNET_i2s (&n->id), "SHUTDOWN_TASK");
992 #endif
993   if (is_connected (n))
994     GNUNET_STATISTICS_update (GST_stats,
995                               gettext_noop
996                               ("# peers disconnected due to global disconnect"),
997                               1, GNUNET_NO);
998   disconnect_neighbour (n);
999   return GNUNET_OK;
1000 }
1001
1002
1003 static void
1004 ats_suggest_cancel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1005 {
1006   struct NeighbourMapEntry *n = cls;
1007
1008   n->ats_suggest = GNUNET_SCHEDULER_NO_TASK;
1009
1010   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1011               " ATS did not suggested address to connect to peer `%s'\n",
1012               GNUNET_i2s (&n->id));
1013
1014   disconnect_neighbour (n);
1015 }
1016
1017 /**
1018  * Cleanup the neighbours subsystem.
1019  */
1020 void
1021 GST_neighbours_stop ()
1022 {
1023   // This can happen during shutdown
1024   if (neighbours == NULL)
1025   {
1026     return;
1027   }
1028
1029   GNUNET_CONTAINER_multihashmap_iterate (neighbours, &disconnect_all_neighbours,
1030                                          NULL);
1031   GNUNET_CONTAINER_multihashmap_destroy (neighbours);
1032   GNUNET_assert (neighbours_connected == 0);
1033   neighbours = NULL;
1034   callback_cls = NULL;
1035   connect_notify_cb = NULL;
1036   disconnect_notify_cb = NULL;
1037 }
1038
1039
1040 /**
1041  * We tried to send a SESSION_CONNECT message to another peer.  If this
1042  * succeeded, we change the state.  If it failed, we should tell
1043  * ATS to not use this address anymore (until it is re-validated).
1044  *
1045  * @param cls the 'struct NeighbourMapEntry'
1046  * @param success GNUNET_OK on success
1047  */
1048 static void
1049 send_connect_continuation (void *cls, const struct GNUNET_PeerIdentity *target,
1050                            int success)
1051 {
1052   struct NeighbourMapEntry *n = cls;
1053
1054   GNUNET_assert (n != NULL);
1055   GNUNET_assert (!is_connected (n));
1056
1057   if (is_disconnecting (n))
1058     return;                     /* neighbour is going away */
1059
1060   if (GNUNET_YES != success)
1061   {
1062 #if DEBUG_TRANSPORT
1063     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1064                 "Failed to send CONNECT_MSG to peer `%4s' with plugin `%s' address '%s' session %X, asking ATS for new address \n",
1065                 GNUNET_i2s (&n->id), n->address->transport_name,
1066                 (n->addrlen ==
1067                  0) ? "<inbound>" : GST_plugins_a2s (n->address), n->session);
1068 #endif
1069
1070     GNUNET_ATS_address_destroyed (GST_ats, n->address, NULL);
1071
1072     change_state (n, S_NOT_CONNECTED);
1073
1074     if (n->ats_suggest != GNUNET_SCHEDULER_NO_TASK)
1075       GNUNET_SCHEDULER_cancel (n->ats_suggest);
1076     n->ats_suggest =
1077         GNUNET_SCHEDULER_add_delayed (ATS_RESPONSE_TIMEOUT, ats_suggest_cancel,
1078                                       n);
1079     GNUNET_ATS_suggest_address (GST_ats, &n->id);
1080     return;
1081   }
1082
1083
1084 }
1085
1086
1087 /**
1088  * We tried to switch addresses with an peer already connected. If it failed,
1089  * we should tell ATS to not use this address anymore (until it is re-validated).
1090  *
1091  * @param cls the 'struct NeighbourMapEntry'
1092  * @param success GNUNET_OK on success
1093  */
1094 static void
1095 send_switch_address_continuation (void *cls,
1096                                   const struct GNUNET_PeerIdentity *target,
1097                                   int success)
1098 {
1099   struct NeighbourMapEntry *n = cls;
1100
1101   GNUNET_assert (n != NULL);
1102   if (is_disconnecting (n))
1103     return;                     /* neighbour is going away */
1104
1105   GNUNET_assert (n->state == S_CONNECTED);
1106   if (GNUNET_YES != success)
1107   {
1108 #if DEBUG_TRANSPORT
1109     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1110                 "Failed to switch connected peer `%s' to plugin `%s' address '%s' session %X, asking ATS for new address \n",
1111                 GNUNET_i2s (&n->id), n->address->transport_name,
1112                 (n->addrlen ==
1113                  0) ? "<inbound>" : GST_plugins_a2s (n->address), n->session);
1114 #endif
1115
1116     GNUNET_ATS_address_destroyed (GST_ats, n->address, NULL);
1117
1118     if (n->ats_suggest != GNUNET_SCHEDULER_NO_TASK)
1119       GNUNET_SCHEDULER_cancel (n->ats_suggest);
1120     n->ats_suggest =
1121         GNUNET_SCHEDULER_add_delayed (ATS_RESPONSE_TIMEOUT, ats_suggest_cancel,
1122                                       n);
1123     GNUNET_ATS_suggest_address (GST_ats, &n->id);
1124     return;
1125   }
1126   /* Tell ATS that switching addresses was successful */
1127   GNUNET_ATS_address_in_use (GST_ats, n->address, n->session, GNUNET_YES);
1128 }
1129
1130 /**
1131  * We tried to send a SESSION_CONNECT message to another peer.  If this
1132  * succeeded, we change the state.  If it failed, we should tell
1133  * ATS to not use this address anymore (until it is re-validated).
1134  *
1135  * @param cls the 'struct NeighbourMapEntry'
1136  * @param success GNUNET_OK on success
1137  */
1138 static void
1139 send_connect_ack_continuation (void *cls,
1140                                const struct GNUNET_PeerIdentity *target,
1141                                int success)
1142 {
1143   struct NeighbourMapEntry *n = cls;
1144
1145   GNUNET_assert (n != NULL);
1146
1147   if (GNUNET_YES == success)
1148     return;                     /* sending successful */
1149
1150   /* sending failed, ask for next address  */
1151 #if DEBUG_TRANSPORT
1152   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1153               "Failed to send CONNECT_MSG to peer `%4s' with plugin `%s' address '%s' session %X, asking ATS for new address \n",
1154               GNUNET_i2s (&n->id), n->address->transport_name,
1155               (n->addrlen == 0) ? "<inbound>" : GST_plugins_a2s (n->address),
1156               n->session);
1157 #endif
1158   change_state (n, S_NOT_CONNECTED);
1159
1160   GNUNET_ATS_address_destroyed (GST_ats, n->address, NULL);
1161
1162   if (n->ats_suggest != GNUNET_SCHEDULER_NO_TASK)
1163     GNUNET_SCHEDULER_cancel (n->ats_suggest);
1164   n->ats_suggest =
1165       GNUNET_SCHEDULER_add_delayed (ATS_RESPONSE_TIMEOUT, ats_suggest_cancel,
1166                                     n);
1167   GNUNET_ATS_suggest_address (GST_ats, &n->id);
1168 }
1169
1170 /**
1171  * For an existing neighbour record, set the active connection to
1172  * the given address.
1173  *
1174  * @param peer identity of the peer to switch the address for
1175  * @param address address of the other peer, NULL if other peer
1176  *                       connected to us
1177  * @param session session to use (or NULL)
1178  * @param ats performance data
1179  * @param ats_count number of entries in ats
1180  * @return GNUNET_YES if we are currently connected, GNUNET_NO if the
1181  *         connection is not up (yet)
1182  */
1183 int
1184 GST_neighbours_switch_to_address_3way (const struct GNUNET_PeerIdentity *peer,
1185                                        const struct GNUNET_HELLO_Address *address,
1186                                        struct Session *session,
1187                                        const struct GNUNET_ATS_Information *ats,
1188                                        uint32_t ats_count,
1189                                        struct GNUNET_BANDWIDTH_Value32NBO
1190                                        bandwidth_in,
1191                                        struct GNUNET_BANDWIDTH_Value32NBO
1192                                        bandwidth_out)
1193 {
1194   struct NeighbourMapEntry *n;
1195   struct SessionConnectMessage connect_msg;
1196   size_t msg_len;
1197   size_t ret;
1198   int checks_failed;
1199
1200   // This can happen during shutdown
1201   if (neighbours == NULL)
1202   {
1203     return GNUNET_NO;
1204   }
1205
1206   checks_failed = GNUNET_NO;
1207
1208   if (address == NULL)
1209   {
1210     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1211                 "ATS offered suggested us empty address: plugin NULL");
1212     GNUNET_break_op (0);
1213     checks_failed = GNUNET_YES;
1214   }
1215   if ( (session == NULL) && (address == NULL) )
1216   {
1217     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1218                 "ATS offered suggested us empty address: address NULL & session NULL");
1219     GNUNET_break_op (0);
1220     checks_failed = GNUNET_YES;
1221   }
1222
1223   n = lookup_neighbour (peer);
1224   if (NULL == n)
1225     checks_failed = GNUNET_YES;
1226
1227   if (checks_failed == GNUNET_YES)
1228   {
1229     GNUNET_ATS_address_destroyed (GST_ats, address, session);
1230     if (n != NULL)
1231       GNUNET_ATS_suggest_address (GST_ats, peer);
1232     return GNUNET_NO;
1233   }
1234
1235   /* checks successful and neighbour != NULL */
1236 #if DEBUG_TRANSPORT
1237   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1238               "ATS tells us to switch to plugin `%s' address '%s' session %X for %s peer `%s'\n",
1239               address->transport_name,
1240               (address_len == 0) ? "<inbound>" : GST_plugins_a2s (address),
1241               session, (is_connected (n) ? "CONNECTED" : "NOT CONNECTED"),
1242               GNUNET_i2s (peer));
1243 #endif
1244
1245   if (n->ats_suggest != GNUNET_SCHEDULER_NO_TASK)
1246   {
1247     GNUNET_SCHEDULER_cancel (n->ats_suggest);
1248     n->ats_suggest = GNUNET_SCHEDULER_NO_TASK;
1249   }
1250
1251   // do not switch addresses just update quotas
1252   if ( (is_connected (n)) && 
1253        (0 == GNUNET_HELLO_address_cmp (address,
1254                                        n->address)) &&
1255        (n->session == session) )
1256   {
1257     struct QuotaSetMessage q_msg;
1258     
1259 #if DEBUG_TRANSPORT
1260     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1261                 "Sending outbound quota of %u Bps and inbound quota of %u Bps for peer `%s' to all clients\n",
1262                 ntohl (n->bandwidth_out.value__),
1263                 ntohl (n->bandwidth_in.value__), GNUNET_i2s (peer));
1264 #endif
1265     
1266     n->bandwidth_in = bandwidth_in;
1267     n->bandwidth_out = bandwidth_out;
1268     GST_neighbours_set_incoming_quota (&n->id, n->bandwidth_in);
1269     
1270     q_msg.header.size = htons (sizeof (struct QuotaSetMessage));
1271     q_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA);
1272     q_msg.quota = n->bandwidth_out;
1273     q_msg.peer = (*peer);
1274     GST_clients_broadcast (&q_msg.header, GNUNET_NO);
1275     return GNUNET_NO;    
1276   }
1277   if (n->state == S_CONNECTED) 
1278     GST_validation_set_address_use (&n->id,
1279                                     n->address,
1280                                     n->session,
1281                                     GNUNET_NO);
1282   /* This will be a connection switch, tell ATS about it */
1283   if (n->state == S_CONNECTED)
1284   {
1285     GNUNET_ATS_address_in_use (GST_ats, n->address, n->session, GNUNET_NO);
1286   }
1287
1288   /* set new address */
1289   if (NULL != n->address)
1290   GNUNET_HELLO_address_free (n->address);
1291   n->address = GNUNET_HELLO_address_copy (address);
1292   n->bandwidth_in = bandwidth_in;
1293   n->bandwidth_out = bandwidth_out;
1294   n->session = session;
1295   GNUNET_SCHEDULER_cancel (n->timeout_task);
1296   n->timeout_task =
1297       GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1298                                     &neighbour_timeout_task, n);
1299   if (n->state == S_CONNECTED)
1300     GST_validation_set_address_use (&n->id,
1301                                     n->address,
1302                                     n->session,
1303                                     GNUNET_YES);
1304
1305
1306   if (n->state == S_DISCONNECT)
1307   {
1308     /* We are disconnecting, nothing to do here */
1309     return GNUNET_NO;
1310   }
1311   /* We are not connected/connecting and initiate a fresh connect */
1312   if (n->state == S_NOT_CONNECTED)
1313   {
1314     msg_len = sizeof (struct SessionConnectMessage);
1315     connect_msg.header.size = htons (msg_len);
1316     connect_msg.header.type =
1317         htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT);
1318     connect_msg.reserved = htonl (0);
1319     connect_msg.timestamp =
1320         GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1321
1322     change_state (n, S_CONNECT_SENT);
1323
1324     ret =
1325         send_with_plugin (peer, (const char *) &connect_msg, msg_len,
1326                           UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_REL, session,
1327                           address, GNUNET_YES,
1328                           &send_connect_continuation, n);
1329
1330
1331     return GNUNET_NO;
1332   }
1333   /* We received a CONNECT message and asked ATS for an address */
1334   else if (n->state == S_CONNECT_RECV)
1335   {
1336     msg_len = sizeof (struct SessionConnectMessage);
1337     connect_msg.header.size = htons (msg_len);
1338     connect_msg.header.type =
1339         htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT_ACK);
1340     connect_msg.reserved = htonl (0);
1341     connect_msg.timestamp =
1342         GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1343
1344     ret =
1345         send_with_plugin (&n->id, (const void *) &connect_msg, msg_len,
1346                           UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_REL, session,
1347                           address, GNUNET_YES,
1348                           &send_connect_ack_continuation, n);
1349     return GNUNET_NO;
1350   }
1351   /* connected peer is switching addresses */
1352   else if (n->state == S_CONNECTED)
1353   {
1354     msg_len = sizeof (struct SessionConnectMessage);
1355     connect_msg.header.size = htons (msg_len);
1356     connect_msg.header.type =
1357         htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT);
1358     connect_msg.reserved = htonl (0);
1359     connect_msg.timestamp =
1360         GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1361
1362     ret =
1363         send_with_plugin (peer, (const char *) &connect_msg, msg_len,
1364                           UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_REL, session,
1365                           address, GNUNET_YES,
1366                           &send_switch_address_continuation, n);
1367     if (ret == GNUNET_SYSERR)
1368     {
1369       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1370                   "Failed to send CONNECT_MESSAGE to `%4s' using address '%s' session %X\n",
1371                   GNUNET_i2s (peer), 
1372                   GST_plugins_a2s (address), session);
1373     }
1374     return GNUNET_NO;
1375   }
1376   else if (n->state == S_CONNECT_SENT)
1377   {
1378     return GNUNET_NO;
1379   }
1380   GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1381               "Invalid connection state to switch addresses %u \n", n->state);
1382   GNUNET_break_op (0);
1383   return GNUNET_NO;
1384 }
1385
1386
1387 /**
1388  * Obtain current latency information for the given neighbour.
1389  *
1390  * @param peer 
1391  * @return observed latency of the address, FOREVER if the address was
1392  *         never successfully validated
1393  */
1394 struct GNUNET_TIME_Relative
1395 GST_neighbour_get_latency (const struct GNUNET_PeerIdentity *peer)
1396 {
1397   struct NeighbourMapEntry *n;
1398
1399   n = lookup_neighbour (peer);
1400   if (NULL == n)
1401     return GNUNET_TIME_UNIT_FOREVER_REL;
1402   return GST_validation_get_address_latency (peer,
1403                                              n->address,
1404                                              n->session);
1405 }
1406
1407
1408 /**
1409  * Create an entry in the neighbour map for the given peer
1410  *
1411  * @param peer peer to create an entry for
1412  * @return new neighbour map entry
1413  */
1414 static struct NeighbourMapEntry *
1415 setup_neighbour (const struct GNUNET_PeerIdentity *peer)
1416 {
1417   struct NeighbourMapEntry *n;
1418
1419 #if DEBUG_TRANSPORT
1420   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1421               "Unknown peer `%s', creating new neighbour\n", GNUNET_i2s (peer));
1422 #endif
1423   n = GNUNET_malloc (sizeof (struct NeighbourMapEntry));
1424   n->id = *peer;
1425   n->state = S_NOT_CONNECTED;
1426   GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
1427                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
1428                                  MAX_BANDWIDTH_CARRY_S);
1429   n->timeout_task =
1430       GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1431                                     &neighbour_timeout_task, n);
1432   GNUNET_assert (GNUNET_OK ==
1433                  GNUNET_CONTAINER_multihashmap_put (neighbours,
1434                                                     &n->id.hashPubKey, n,
1435                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1436   return n;
1437 }
1438
1439
1440 /**
1441  * Try to create a connection to the given target (eventually).
1442  *
1443  * @param target peer to try to connect to
1444  */
1445 void
1446 GST_neighbours_try_connect (const struct GNUNET_PeerIdentity *target)
1447 {
1448   struct NeighbourMapEntry *n;
1449
1450   // This can happen during shutdown
1451   if (neighbours == NULL)
1452   {
1453     return;
1454   }
1455 #if DEBUG_TRANSPORT
1456   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Trying to connect to peer `%s'\n",
1457               GNUNET_i2s (target));
1458 #endif
1459   if (0 ==
1460       memcmp (target, &GST_my_identity, sizeof (struct GNUNET_PeerIdentity)))
1461   {
1462     /* my own hello */
1463     return;
1464   }
1465   n = lookup_neighbour (target);
1466
1467   if (NULL != n)
1468   {
1469     if ((is_connected (n)) || (is_connecting (n)))
1470       return;                   /* already connecting or connected */
1471     if (is_disconnecting (n))
1472       change_state (n, S_NOT_CONNECTED);
1473   }
1474
1475
1476   if (n == NULL)
1477     n = setup_neighbour (target);
1478 #if DEBUG_TRANSPORT
1479   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1480               "Asking ATS for suggested address to connect to peer `%s'\n",
1481               GNUNET_i2s (&n->id));
1482 #endif
1483
1484   GNUNET_ATS_suggest_address (GST_ats, &n->id);
1485 }
1486
1487 /**
1488  * Test if we're connected to the given peer.
1489  *
1490  * @param target peer to test
1491  * @return GNUNET_YES if we are connected, GNUNET_NO if not
1492  */
1493 int
1494 GST_neighbours_test_connected (const struct GNUNET_PeerIdentity *target)
1495 {
1496   struct NeighbourMapEntry *n;
1497
1498   // This can happen during shutdown
1499   if (neighbours == NULL)
1500   {
1501     return GNUNET_NO;
1502   }
1503
1504   n = lookup_neighbour (target);
1505
1506   if ((NULL == n) || (!is_connected (n)))
1507     return GNUNET_NO;           /* not connected */
1508   return GNUNET_YES;
1509 }
1510
1511
1512 /**
1513  * A session was terminated. Take note.
1514  *
1515  * @param peer identity of the peer where the session died
1516  * @param session session that is gone
1517  */
1518 void
1519 GST_neighbours_session_terminated (const struct GNUNET_PeerIdentity *peer,
1520                                    struct Session *session)
1521 {
1522   struct NeighbourMapEntry *n;
1523
1524   // This can happen during shutdown
1525   if (neighbours == NULL)
1526   {
1527     return;
1528   }
1529
1530 #if DEBUG_TRANSPORT
1531   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Session %X to peer `%s' ended \n",
1532               session, GNUNET_i2s (peer));
1533 #endif
1534
1535   n = lookup_neighbour (peer);
1536   if (NULL == n)
1537     return;
1538   if (session != n->session)
1539     return;                     /* doesn't affect us */
1540
1541   n->session = NULL;
1542   if (NULL != n->address)
1543   {
1544     GNUNET_HELLO_address_free (n->address);
1545     n->address = NULL;
1546   }
1547
1548   /* not connected anymore anyway, shouldn't matter */
1549   if ((!is_connected (n)) && (!is_connecting (n)))
1550     return;
1551
1552   /* We are connected, so ask ATS to switch addresses */
1553   GNUNET_SCHEDULER_cancel (n->timeout_task);
1554   n->timeout_task =
1555       GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
1556                                     &neighbour_timeout_task, n);
1557   /* try QUICKLY to re-establish a connection, reduce timeout! */
1558   if (n->ats_suggest != GNUNET_SCHEDULER_NO_TASK)
1559     GNUNET_SCHEDULER_cancel (n->ats_suggest);
1560   n->ats_suggest =
1561       GNUNET_SCHEDULER_add_delayed (ATS_RESPONSE_TIMEOUT, ats_suggest_cancel,
1562                                     n);
1563   GNUNET_ATS_suggest_address (GST_ats, peer);
1564 }
1565
1566
1567 /**
1568  * Transmit a message to the given target using the active connection.
1569  *
1570  * @param target destination
1571  * @param msg message to send
1572  * @param msg_size number of bytes in msg
1573  * @param timeout when to fail with timeout
1574  * @param cont function to call when done
1575  * @param cont_cls closure for 'cont'
1576  */
1577 void
1578 GST_neighbours_send (const struct GNUNET_PeerIdentity *target, const void *msg,
1579                      size_t msg_size, struct GNUNET_TIME_Relative timeout,
1580                      GST_NeighbourSendContinuation cont, void *cont_cls)
1581 {
1582   struct NeighbourMapEntry *n;
1583   struct MessageQueue *mq;
1584
1585   // This can happen during shutdown
1586   if (neighbours == NULL)
1587   {
1588     return;
1589   }
1590
1591   n = lookup_neighbour (target);
1592   if ((n == NULL) || (!is_connected (n)))
1593   {
1594     GNUNET_STATISTICS_update (GST_stats,
1595                               gettext_noop
1596                               ("# messages not sent (no such peer or not connected)"),
1597                               1, GNUNET_NO);
1598 #if DEBUG_TRANSPORT
1599     if (n == NULL)
1600       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1601                   "Could not send message to peer `%s': unknown neighbour",
1602                   GNUNET_i2s (target));
1603     else if (!is_connected (n))
1604       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1605                   "Could not send message to peer `%s': not connected\n",
1606                   GNUNET_i2s (target));
1607 #endif
1608     if (NULL != cont)
1609       cont (cont_cls, GNUNET_SYSERR);
1610     return;
1611   }
1612
1613   if ((n->session == NULL) && (n->address == NULL) )
1614   {
1615     GNUNET_STATISTICS_update (GST_stats,
1616                               gettext_noop
1617                               ("# messages not sent (no such peer or not connected)"),
1618                               1, GNUNET_NO);
1619 #if DEBUG_TRANSPORT
1620     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1621                 "Could not send message to peer `%s': no address available\n",
1622                 GNUNET_i2s (target));
1623 #endif
1624
1625     if (NULL != cont)
1626       cont (cont_cls, GNUNET_SYSERR);
1627     return;
1628   }
1629
1630   GNUNET_assert (msg_size >= sizeof (struct GNUNET_MessageHeader));
1631   GNUNET_STATISTICS_update (GST_stats,
1632                             gettext_noop
1633                             ("# bytes in message queue for other peers"),
1634                             msg_size, GNUNET_NO);
1635   mq = GNUNET_malloc (sizeof (struct MessageQueue) + msg_size);
1636   mq->cont = cont;
1637   mq->cont_cls = cont_cls;
1638   /* FIXME: this memcpy can be up to 7% of our total runtime! */
1639   memcpy (&mq[1], msg, msg_size);
1640   mq->message_buf = (const char *) &mq[1];
1641   mq->message_buf_size = msg_size;
1642   mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1643   GNUNET_CONTAINER_DLL_insert_tail (n->messages_head, n->messages_tail, mq);
1644
1645   if ((GNUNET_SCHEDULER_NO_TASK == n->transmission_task) &&
1646       (NULL == n->is_active))
1647     n->transmission_task = GNUNET_SCHEDULER_add_now (&transmission_task, n);
1648 }
1649
1650
1651 /**
1652  * We have received a message from the given sender.  How long should
1653  * we delay before receiving more?  (Also used to keep the peer marked
1654  * as live).
1655  *
1656  * @param sender sender of the message
1657  * @param size size of the message
1658  * @param do_forward set to GNUNET_YES if the message should be forwarded to clients
1659  *                   GNUNET_NO if the neighbour is not connected or violates the quota,
1660  *                   GNUNET_SYSERR if the connection is not fully up yet
1661  * @return how long to wait before reading more from this sender
1662  */
1663 struct GNUNET_TIME_Relative
1664 GST_neighbours_calculate_receive_delay (const struct GNUNET_PeerIdentity
1665                                         *sender, ssize_t size, int *do_forward)
1666 {
1667   struct NeighbourMapEntry *n;
1668   struct GNUNET_TIME_Relative ret;
1669
1670   // This can happen during shutdown
1671   if (neighbours == NULL)
1672   {
1673     return GNUNET_TIME_UNIT_FOREVER_REL;
1674   }
1675
1676   n = lookup_neighbour (sender);
1677   if (n == NULL)
1678   {
1679     GST_neighbours_try_connect (sender);
1680     n = lookup_neighbour (sender);
1681     if (NULL == n)
1682     {
1683       GNUNET_STATISTICS_update (GST_stats,
1684                                 gettext_noop
1685                                 ("# messages discarded due to lack of neighbour record"),
1686                                 1, GNUNET_NO);
1687       *do_forward = GNUNET_NO;
1688       return GNUNET_TIME_UNIT_ZERO;
1689     }
1690   }
1691   if (!is_connected (n))
1692   {
1693     *do_forward = GNUNET_SYSERR;
1694     return GNUNET_TIME_UNIT_ZERO;
1695   }
1696   if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, size))
1697   {
1698     n->quota_violation_count++;
1699 #if DEBUG_TRANSPORT
1700     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1701                 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
1702                 n->in_tracker.available_bytes_per_s__,
1703                 n->quota_violation_count);
1704 #endif
1705     /* Discount 32k per violation */
1706     GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, -32 * 1024);
1707   }
1708   else
1709   {
1710     if (n->quota_violation_count > 0)
1711     {
1712       /* try to add 32k back */
1713       GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, 32 * 1024);
1714       n->quota_violation_count--;
1715     }
1716   }
1717   if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
1718   {
1719     GNUNET_STATISTICS_update (GST_stats,
1720                               gettext_noop
1721                               ("# bandwidth quota violations by other peers"),
1722                               1, GNUNET_NO);
1723     *do_forward = GNUNET_NO;
1724     return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
1725   }
1726   *do_forward = GNUNET_YES;
1727   ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 32 * 1024);
1728   if (ret.rel_value > 0)
1729   {
1730 #if DEBUG_TRANSPORT
1731     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1732                 "Throttling read (%llu bytes excess at %u b/s), waiting %llu ms before reading more.\n",
1733                 (unsigned long long) n->in_tracker.
1734                 consumption_since_last_update__,
1735                 (unsigned int) n->in_tracker.available_bytes_per_s__,
1736                 (unsigned long long) ret.rel_value);
1737 #endif
1738     GNUNET_STATISTICS_update (GST_stats,
1739                               gettext_noop ("# ms throttling suggested"),
1740                               (int64_t) ret.rel_value, GNUNET_NO);
1741   }
1742   return ret;
1743 }
1744
1745
1746 /**
1747  * Keep the connection to the given neighbour alive longer,
1748  * we received a KEEPALIVE (or equivalent).
1749  *
1750  * @param neighbour neighbour to keep alive
1751  */
1752 void
1753 GST_neighbours_keepalive (const struct GNUNET_PeerIdentity *neighbour)
1754 {
1755   struct NeighbourMapEntry *n;
1756
1757   // This can happen during shutdown
1758   if (neighbours == NULL)
1759   {
1760     return;
1761   }
1762
1763   n = lookup_neighbour (neighbour);
1764   if (NULL == n)
1765   {
1766     GNUNET_STATISTICS_update (GST_stats,
1767                               gettext_noop
1768                               ("# KEEPALIVE messages discarded (not connected)"),
1769                               1, GNUNET_NO);
1770     return;
1771   }
1772   GNUNET_SCHEDULER_cancel (n->timeout_task);
1773   n->timeout_task =
1774       GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1775                                     &neighbour_timeout_task, n);
1776 }
1777
1778
1779 /**
1780  * Change the incoming quota for the given peer.
1781  *
1782  * @param neighbour identity of peer to change qutoa for
1783  * @param quota new quota
1784  */
1785 void
1786 GST_neighbours_set_incoming_quota (const struct GNUNET_PeerIdentity *neighbour,
1787                                    struct GNUNET_BANDWIDTH_Value32NBO quota)
1788 {
1789   struct NeighbourMapEntry *n;
1790
1791   // This can happen during shutdown
1792   if (neighbours == NULL)
1793   {
1794     return;
1795   }
1796
1797   n = lookup_neighbour (neighbour);
1798   if (n == NULL)
1799   {
1800     GNUNET_STATISTICS_update (GST_stats,
1801                               gettext_noop
1802                               ("# SET QUOTA messages ignored (no such peer)"),
1803                               1, GNUNET_NO);
1804     return;
1805   }
1806   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker, quota);
1807   if (0 != ntohl (quota.value__))
1808     return;
1809 #if DEBUG_TRANSPORT
1810   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting peer `%4s' due to `%s'\n",
1811               GNUNET_i2s (&n->id), "SET_QUOTA");
1812 #endif
1813   if (is_connected (n))
1814     GNUNET_STATISTICS_update (GST_stats,
1815                               gettext_noop ("# disconnects due to quota of 0"),
1816                               1, GNUNET_NO);
1817   disconnect_neighbour (n);
1818 }
1819
1820
1821 /**
1822  * Closure for the neighbours_iterate function.
1823  */
1824 struct IteratorContext
1825 {
1826   /**
1827    * Function to call on each connected neighbour.
1828    */
1829   GST_NeighbourIterator cb;
1830
1831   /**
1832    * Closure for 'cb'.
1833    */
1834   void *cb_cls;
1835 };
1836
1837
1838 /**
1839  * Call the callback from the closure for each connected neighbour.
1840  *
1841  * @param cls the 'struct IteratorContext'
1842  * @param key the hash of the public key of the neighbour
1843  * @param value the 'struct NeighbourMapEntry'
1844  * @return GNUNET_OK (continue to iterate)
1845  */
1846 static int
1847 neighbours_iterate (void *cls, const GNUNET_HashCode * key, void *value)
1848 {
1849   struct IteratorContext *ic = cls;
1850   struct NeighbourMapEntry *n = value;
1851
1852   if (!is_connected (n))
1853     return GNUNET_OK;
1854
1855   ic->cb (ic->cb_cls, &n->id, NULL, 0, n->address);
1856   return GNUNET_OK;
1857 }
1858
1859
1860 /**
1861  * Iterate over all connected neighbours.
1862  *
1863  * @param cb function to call
1864  * @param cb_cls closure for cb
1865  */
1866 void
1867 GST_neighbours_iterate (GST_NeighbourIterator cb, void *cb_cls)
1868 {
1869   struct IteratorContext ic;
1870
1871   // This can happen during shutdown
1872   if (neighbours == NULL)
1873   {
1874     return;
1875   }
1876
1877   ic.cb = cb;
1878   ic.cb_cls = cb_cls;
1879   GNUNET_CONTAINER_multihashmap_iterate (neighbours, &neighbours_iterate, &ic);
1880 }
1881
1882 /**
1883  * If we have an active connection to the given target, it must be shutdown.
1884  *
1885  * @param target peer to disconnect from
1886  */
1887 void
1888 GST_neighbours_force_disconnect (const struct GNUNET_PeerIdentity *target)
1889 {
1890   struct NeighbourMapEntry *n;
1891
1892   // This can happen during shutdown
1893   if (neighbours == NULL)
1894   {
1895     return;
1896   }
1897
1898   n = lookup_neighbour (target);
1899   if (NULL == n)
1900     return;                     /* not active */
1901   if (is_connected (n))
1902   {
1903     send_disconnect (&n->id, n->address, n->session);
1904
1905     n = lookup_neighbour (target);
1906     if (NULL == n)
1907       return;                   /* gone already */
1908   }
1909   disconnect_neighbour (n);
1910 }
1911
1912
1913 /**
1914  * We received a disconnect message from the given peer,
1915  * validate and process.
1916  *
1917  * @param peer sender of the message
1918  * @param msg the disconnect message
1919  */
1920 void
1921 GST_neighbours_handle_disconnect_message (const struct GNUNET_PeerIdentity
1922                                           *peer,
1923                                           const struct GNUNET_MessageHeader
1924                                           *msg)
1925 {
1926   struct NeighbourMapEntry *n;
1927   const struct SessionDisconnectMessage *sdm;
1928   GNUNET_HashCode hc;
1929
1930 #if DEBUG_TRANSPORT
1931   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1932               "Received DISCONNECT message from peer `%s'\n",
1933               GNUNET_i2s (peer));
1934 #endif
1935
1936   if (ntohs (msg->size) != sizeof (struct SessionDisconnectMessage))
1937   {
1938     // GNUNET_break_op (0);
1939     GNUNET_STATISTICS_update (GST_stats,
1940                               gettext_noop
1941                               ("# disconnect messages ignored (old format)"), 1,
1942                               GNUNET_NO);
1943     return;
1944   }
1945   sdm = (const struct SessionDisconnectMessage *) msg;
1946   n = lookup_neighbour (peer);
1947   if (NULL == n)
1948     return;                     /* gone already */
1949   if (GNUNET_TIME_absolute_ntoh (sdm->timestamp).abs_value <=
1950       n->connect_ts.abs_value)
1951   {
1952     GNUNET_STATISTICS_update (GST_stats,
1953                               gettext_noop
1954                               ("# disconnect messages ignored (timestamp)"), 1,
1955                               GNUNET_NO);
1956     return;
1957   }
1958   GNUNET_CRYPTO_hash (&sdm->public_key,
1959                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1960                       &hc);
1961   if (0 != memcmp (peer, &hc, sizeof (struct GNUNET_PeerIdentity)))
1962   {
1963     GNUNET_break_op (0);
1964     return;
1965   }
1966   if (ntohl (sdm->purpose.size) !=
1967       sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
1968       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
1969       sizeof (struct GNUNET_TIME_AbsoluteNBO))
1970   {
1971     GNUNET_break_op (0);
1972     return;
1973   }
1974   if (GNUNET_OK !=
1975       GNUNET_CRYPTO_rsa_verify
1976       (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT, &sdm->purpose,
1977        &sdm->signature, &sdm->public_key))
1978   {
1979     GNUNET_break_op (0);
1980     return;
1981   }
1982   GST_neighbours_force_disconnect (peer);
1983 }
1984
1985
1986 /**
1987  * We received a 'SESSION_CONNECT_ACK' message from the other peer.
1988  * Consider switching to it.
1989  *
1990  * @param message possibly a 'struct SessionConnectMessage' (check format)
1991  * @param peer identity of the peer to switch the address for
1992  * @param address address of the other peer, NULL if other peer
1993  *                       connected to us
1994  * @param session session to use (or NULL)
1995  * @param ats performance data
1996  * @param ats_count number of entries in ats
1997  */
1998 void
1999 GST_neighbours_handle_connect_ack (const struct GNUNET_MessageHeader *message,
2000                                    const struct GNUNET_PeerIdentity *peer,
2001                                    const struct GNUNET_HELLO_Address *address,
2002                                    struct Session *session,
2003                                    const struct GNUNET_ATS_Information *ats,
2004                                    uint32_t ats_count)
2005 {
2006   const struct SessionConnectMessage *scm;
2007   struct QuotaSetMessage q_msg;
2008   struct GNUNET_MessageHeader msg;
2009   struct NeighbourMapEntry *n;
2010   size_t msg_len;
2011   size_t ret;
2012   int was_connected;
2013
2014 #if DEBUG_TRANSPORT
2015   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2016               "Received CONNECT_ACK message from peer `%s'\n",
2017               GNUNET_i2s (peer));
2018 #endif
2019
2020   if (ntohs (message->size) != sizeof (struct SessionConnectMessage))
2021   {
2022     GNUNET_break_op (0);
2023     return;
2024   }
2025
2026   scm = (const struct SessionConnectMessage *) message;
2027   GNUNET_break_op (ntohl (scm->reserved) == 0);
2028   n = lookup_neighbour (peer);
2029   if (NULL == n)
2030     n = setup_neighbour (peer);
2031
2032   if (!is_connecting(n))
2033   {
2034     GNUNET_STATISTICS_update (GST_stats,
2035         gettext_noop ("# unexpected CONNECT_ACK messages"), 1,
2036         GNUNET_NO);
2037     return;
2038   }
2039
2040   if (NULL != session)
2041     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2042                      "transport-ats",
2043                      "Giving ATS session %p of plugin %s for peer %s\n",
2044                      session, address->transport_name, GNUNET_i2s (peer));
2045   GNUNET_ATS_address_update (GST_ats, address, session, ats, ats_count);
2046
2047   was_connected = is_connected (n);
2048   if (!is_connected (n))
2049   {
2050     change_state (n, S_CONNECTED);
2051     GST_validation_set_address_use (&n->id,
2052                                     n->address,
2053                                     n->session,
2054                                     GNUNET_YES);
2055   }
2056
2057   GNUNET_ATS_address_in_use (GST_ats, n->address, NULL, GNUNET_YES);
2058
2059 #if DEBUG_TRANSPORT
2060   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2061               "Setting inbound quota of %u for peer `%s' to \n",
2062               ntohl (n->bandwidth_in.value__), GNUNET_i2s (&n->id));
2063 #endif
2064   GST_neighbours_set_incoming_quota (&n->id, n->bandwidth_in);
2065
2066   /* send ACK (ACK) */
2067   msg_len = sizeof (msg);
2068   msg.size = htons (msg_len);
2069   msg.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_ACK);
2070
2071   ret =
2072       send_with_plugin (&n->id, (const char *) &msg, msg_len, UINT32_MAX,
2073                         GNUNET_TIME_UNIT_FOREVER_REL, n->session,
2074                         n->address, GNUNET_YES, NULL,
2075                         NULL);
2076
2077   if (ret == GNUNET_SYSERR)
2078     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2079                 "Failed to send SESSION_ACK to `%4s' using address '%s' session %X\n",
2080                 GNUNET_i2s (&n->id), 
2081                 GST_plugins_a2s (n->address), n->session);
2082
2083
2084   if (!was_connected)
2085   {
2086     if (n->keepalive_task == GNUNET_SCHEDULER_NO_TASK)
2087       n->keepalive_task =
2088           GNUNET_SCHEDULER_add_delayed (KEEPALIVE_FREQUENCY,
2089                                         &neighbour_keepalive_task, n);
2090
2091     neighbours_connected++;
2092     GNUNET_STATISTICS_update (GST_stats, gettext_noop ("# peers connected"), 1,
2093                               GNUNET_NO);
2094 #if DEBUG_TRANSPORT
2095     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2096                 "Notify about connect of `%4s' using address '%s' session %X LINE %u\n",
2097                 GNUNET_i2s (&n->id),
2098                 GST_plugins_a2s (n->address), n->session,
2099                 __LINE__);
2100 #endif
2101     connect_notify_cb (callback_cls, &n->id, ats, ats_count);
2102   }
2103
2104 #if DEBUG_TRANSPORT
2105   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2106               "Sending outbound quota of %u Bps for peer `%s' to all clients\n",
2107               ntohl (n->bandwidth_out.value__), GNUNET_i2s (peer));
2108 #endif
2109   q_msg.header.size = htons (sizeof (struct QuotaSetMessage));
2110   q_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA);
2111   q_msg.quota = n->bandwidth_out;
2112   q_msg.peer = (*peer);
2113   GST_clients_broadcast (&q_msg.header, GNUNET_NO);
2114
2115 }
2116
2117 void
2118 GST_neighbours_handle_ack (const struct GNUNET_MessageHeader *message,
2119                            const struct GNUNET_PeerIdentity *peer,
2120                            const struct GNUNET_HELLO_Address *address,
2121                            struct Session *session,
2122                            const struct GNUNET_ATS_Information *ats,
2123                            uint32_t ats_count)
2124 {
2125   struct NeighbourMapEntry *n;
2126   struct QuotaSetMessage q_msg;
2127   int was_connected;
2128
2129 #if DEBUG_TRANSPORT
2130   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received ACK message from peer `%s'\n",
2131               GNUNET_i2s (peer));
2132 #endif
2133
2134   if (ntohs (message->size) != sizeof (struct GNUNET_MessageHeader))
2135   {
2136     GNUNET_break_op (0);
2137     return;
2138   }
2139
2140   n = lookup_neighbour (peer);
2141   if (NULL == n)
2142   {
2143     send_disconnect (peer, address,
2144                      session);
2145     GNUNET_break (0);
2146     return;
2147   }
2148
2149   if (is_connected (n))
2150     return;
2151
2152   if (!is_connecting(n))
2153   {
2154     GNUNET_STATISTICS_update (GST_stats, gettext_noop ("# unexpected ACK messages"), 1,
2155                               GNUNET_NO);
2156     return;
2157   }
2158
2159   if (NULL != session)
2160     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2161                      "transport-ats",
2162                      "Giving ATS session %p of plugin %s for peer %s\n",
2163                      session, address->transport_name, GNUNET_i2s (peer));
2164   GNUNET_ATS_address_update (GST_ats, address, session, ats, ats_count);
2165
2166   was_connected = is_connected (n);
2167   change_state (n, S_CONNECTED);
2168
2169   GNUNET_ATS_address_in_use (GST_ats, n->address, n->session, GNUNET_YES);
2170
2171   GST_neighbours_set_incoming_quota (&n->id, n->bandwidth_in);
2172
2173   if (n->keepalive_task == GNUNET_SCHEDULER_NO_TASK)
2174     n->keepalive_task =
2175         GNUNET_SCHEDULER_add_delayed (KEEPALIVE_FREQUENCY,
2176                                       &neighbour_keepalive_task, n);
2177
2178   if (!was_connected)
2179   {
2180     GST_validation_set_address_use (&n->id,
2181                                     n->address,
2182                                     n->session,
2183                                     GNUNET_YES);
2184     neighbours_connected++;
2185     GNUNET_STATISTICS_update (GST_stats, gettext_noop ("# peers connected"), 1,
2186                               GNUNET_NO);
2187
2188 #if DEBUG_TRANSPORT
2189     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2190                 "Notify about connect of `%4s' using address '%s' session %X LINE %u\n",
2191                 GNUNET_i2s (&n->id),
2192                 GST_plugins_a2s (n->address), n->session,
2193                 __LINE__);
2194 #endif
2195     connect_notify_cb (callback_cls, &n->id, ats, ats_count);
2196   }
2197 #if DEBUG_TRANSPORT
2198   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2199               "Sending outbound quota of %u Bps for peer `%s' to all clients\n",
2200               ntohl (n->bandwidth_out.value__), GNUNET_i2s (peer));
2201 #endif
2202   q_msg.header.size = htons (sizeof (struct QuotaSetMessage));
2203   q_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA);
2204   q_msg.quota = n->bandwidth_out;
2205   q_msg.peer = (*peer);
2206   GST_clients_broadcast (&q_msg.header, GNUNET_NO);
2207 }
2208
2209 struct BlackListCheckContext
2210 {
2211   struct GNUNET_ATS_Information *ats;
2212
2213   uint32_t ats_count;
2214
2215   struct Session *session;
2216
2217   struct GNUNET_HELLO_Address *address;
2218
2219   struct GNUNET_TIME_Absolute ts;
2220 };
2221
2222
2223 static void
2224 handle_connect_blacklist_cont (void *cls,
2225                                const struct GNUNET_PeerIdentity *peer,
2226                                int result)
2227 {
2228   struct NeighbourMapEntry *n;
2229   struct BlackListCheckContext *bcc = cls;
2230
2231 #if DEBUG_TRANSPORT
2232   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2233               "Blacklist check due to CONNECT message: `%s'\n",
2234               GNUNET_i2s (peer),
2235               (result == GNUNET_OK) ? "ALLOWED" : "FORBIDDEN");
2236 #endif
2237
2238   /* not allowed */
2239   if (GNUNET_OK != result)
2240   {
2241     GNUNET_HELLO_address_free (bcc->address);
2242     GNUNET_free (bcc);
2243     return;
2244   }
2245
2246   n = lookup_neighbour (peer);
2247   if (NULL == n)
2248     n = setup_neighbour (peer);
2249
2250   if (bcc->ts.abs_value > n->connect_ts.abs_value)
2251   {
2252     if (NULL != bcc->session)
2253       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2254                        "transport-ats",
2255                        "Giving ATS session %p of address `%s' for peer %s\n",
2256                        bcc->session, 
2257                        GST_plugins_a2s (bcc->address),
2258                        GNUNET_i2s (peer));
2259     GNUNET_ATS_address_update (GST_ats, bcc->address,
2260                                bcc->session, bcc->ats, bcc->ats_count);
2261     n->connect_ts = bcc->ts;
2262   }
2263
2264   GNUNET_free (bcc);
2265
2266   if (n->state != S_CONNECT_RECV)
2267     change_state (n, S_CONNECT_RECV);
2268
2269   /* Ask ATS for an address to connect via that address */
2270   if (n->ats_suggest != GNUNET_SCHEDULER_NO_TASK)
2271     GNUNET_SCHEDULER_cancel (n->ats_suggest);
2272   n->ats_suggest =
2273       GNUNET_SCHEDULER_add_delayed (ATS_RESPONSE_TIMEOUT, ats_suggest_cancel,
2274                                     n);
2275   GNUNET_ATS_suggest_address (GST_ats, peer);
2276 }
2277
2278 /**
2279  * We received a 'SESSION_CONNECT' message from the other peer.
2280  * Consider switching to it.
2281  *
2282  * @param message possibly a 'struct SessionConnectMessage' (check format)
2283  * @param peer identity of the peer to switch the address for
2284  * @param address address of the other peer, NULL if other peer
2285  *                       connected to us
2286  * @param session session to use (or NULL)
2287  * @param ats performance data
2288  * @param ats_count number of entries in ats (excluding 0-termination)
2289  */
2290 void
2291 GST_neighbours_handle_connect (const struct GNUNET_MessageHeader *message,
2292                                const struct GNUNET_PeerIdentity *peer,
2293                                const struct GNUNET_HELLO_Address *address,
2294                                struct Session *session,
2295                                const struct GNUNET_ATS_Information *ats,
2296                                uint32_t ats_count)
2297 {
2298   const struct SessionConnectMessage *scm;
2299   struct NeighbourMapEntry *n;
2300   struct BlackListCheckContext *bcc = NULL;
2301
2302 #if DEBUG_TRANSPORT
2303   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2304               "Received CONNECT message from peer `%s'\n", GNUNET_i2s (peer));
2305 #endif
2306
2307   if (ntohs (message->size) != sizeof (struct SessionConnectMessage))
2308   {
2309     GNUNET_break_op (0);
2310     return;
2311   }
2312
2313   scm = (const struct SessionConnectMessage *) message;
2314   GNUNET_break_op (ntohl (scm->reserved) == 0);
2315
2316   n = lookup_neighbour (peer);
2317   if (n != NULL)
2318   {
2319     /* connected peer switches addresses */
2320     if (is_connected (n))
2321     {
2322       GNUNET_ATS_address_update (GST_ats, address, session, ats, ats_count);
2323       return;
2324     }
2325   }
2326
2327   /* we are not connected to this peer */
2328   /* do blacklist check */
2329   bcc =
2330       GNUNET_malloc (sizeof (struct BlackListCheckContext) +
2331                      sizeof (struct GNUNET_ATS_Information) * (ats_count + 1));
2332   bcc->ts = GNUNET_TIME_absolute_ntoh (scm->timestamp);
2333   bcc->ats_count = ats_count + 1;
2334   bcc->address = GNUNET_HELLO_address_copy (address);
2335   bcc->session = session;
2336   bcc->ats = (struct GNUNET_ATS_Information *) &bcc[1];
2337   memcpy (bcc->ats, ats, sizeof (struct GNUNET_ATS_Information) * ats_count);
2338   bcc->ats[ats_count].type = htonl (GNUNET_ATS_QUALITY_NET_DELAY);
2339   bcc->ats[ats_count].value = htonl ((uint32_t) GST_neighbour_get_latency (peer).rel_value);
2340   GST_blacklist_test_allowed (peer, address->transport_name, handle_connect_blacklist_cont,
2341                               bcc);
2342 }
2343
2344
2345 /* end of file gnunet-service-transport_neighbours.c */