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