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