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