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