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