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