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