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