possible fix for 1844
[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_constants.h"
35 #include "transport.h"
36
37
38 /**
39  * Size of the neighbour hash map.
40  */
41 #define NEIGHBOUR_TABLE_SIZE 256
42
43 /**
44  * How often must a peer violate bandwidth quotas before we start
45  * to simply drop its messages?
46  */
47 #define QUOTA_VIOLATION_DROP_THRESHOLD 10
48
49 /**
50  * How often do we send KEEPALIVE messages to each of our neighbours?
51  * (idle timeout is 5 minutes or 300 seconds, so with 90s interval we
52  * send 3 keepalives in each interval, so 3 messages would need to be
53  * lost in a row for a disconnect).
54  */
55 #define KEEPALIVE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 90)
56
57
58 /**
59  * Entry in neighbours.
60  */
61 struct NeighbourMapEntry;
62
63 /**
64  * Message a peer sends to another to indicate its
65  * preference for communicating via a particular
66  * session (and the desire to establish a real
67  * connection).
68  */
69 struct SessionConnectMessage
70 {
71   /**
72    * Header of type 'GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT'
73    */
74   struct GNUNET_MessageHeader header;
75
76   /**
77    * Always zero.
78    */
79   uint32_t reserved GNUNET_PACKED;
80
81   /**
82    * Absolute time at the sender.  Only the most recent connect
83    * message implies which session is preferred by the sender.
84    */
85   struct GNUNET_TIME_AbsoluteNBO timestamp;
86
87 };
88
89
90 struct SessionDisconnectMessage
91 {
92   /**
93    * Header of type 'GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT'
94    */
95   struct GNUNET_MessageHeader header;
96
97   /**
98    * Always zero.
99    */
100   uint32_t reserved GNUNET_PACKED;
101
102   /**
103    * Purpose of the signature.  Extends over the timestamp.
104    * Purpose should be GNUNET_SIGNATURE_PURPOSE_TRANSPORT_DISCONNECT.
105    */
106   struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
107
108   /**
109    * Absolute time at the sender.  Only the most recent connect
110    * message implies which session is preferred by the sender.
111    */
112   struct GNUNET_TIME_AbsoluteNBO timestamp;
113
114   /**
115    * Public key of the sender.
116    */
117   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded public_key;
118   
119   /**
120    * Signature of the peer that sends us the disconnect.  Only
121    * valid if the timestamp is AFTER the timestamp from the
122    * corresponding 'CONNECT' message.
123    */
124   struct GNUNET_CRYPTO_RsaSignature signature;
125
126 };
127
128
129 /**
130  * For each neighbour we keep a list of messages
131  * that we still want to transmit to the neighbour.
132  */
133 struct MessageQueue
134 {
135
136   /**
137    * This is a doubly linked list.
138    */
139   struct MessageQueue *next;
140
141   /**
142    * This is a doubly linked list.
143    */
144   struct MessageQueue *prev;
145
146   /**
147    * Once this message is actively being transmitted, which
148    * neighbour is it associated with?
149    */
150   struct NeighbourMapEntry *n;
151
152   /**
153    * Function to call once we're done.
154    */
155   GST_NeighbourSendContinuation cont;
156
157   /**
158    * Closure for 'cont'
159    */
160   void *cont_cls;
161
162   /**
163    * The message(s) we want to transmit, GNUNET_MessageHeader(s)
164    * stuck together in memory.  Allocated at the end of this struct.
165    */
166   const char *message_buf;
167
168   /**
169    * Size of the message buf
170    */
171   size_t message_buf_size;
172
173   /**
174    * At what time should we fail?
175    */
176   struct GNUNET_TIME_Absolute timeout;
177
178 };
179
180
181 /**
182  * Entry in neighbours.
183  */
184 struct NeighbourMapEntry
185 {
186
187   /**
188    * Head of list of messages we would like to send to this peer;
189    * must contain at most one message per client.
190    */
191   struct MessageQueue *messages_head;
192
193   /**
194    * Tail of list of messages we would like to send to this peer; must
195    * contain at most one message per client.
196    */
197   struct MessageQueue *messages_tail;
198
199   /**
200    * Performance data for the peer.
201    */
202   //struct GNUNET_ATS_Information *ats;
203
204   /**
205    * Are we currently trying to send a message? If so, which one?
206    */
207   struct MessageQueue *is_active;
208
209   /**
210    * Active session for communicating with the peer.
211    */
212   struct Session *session;
213
214   /**
215    * Name of the plugin we currently use.
216    */
217   char *plugin_name;
218
219   /**
220    * Address used for communicating with the peer, NULL for inbound connections.
221    */
222   void *addr;
223
224   /**
225    * Number of bytes in 'addr'.
226    */
227   size_t addrlen;
228
229   /**
230    * Identity of this neighbour.
231    */
232   struct GNUNET_PeerIdentity id;
233
234   /**
235    * ID of task scheduled to run when this peer is about to
236    * time out (will free resources associated with the peer).
237    */
238   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
239
240   /**
241    * ID of task scheduled to send keepalives.
242    */
243   GNUNET_SCHEDULER_TaskIdentifier keepalive_task;
244
245   /**
246    * ID of task scheduled to run when we should try transmitting
247    * the head of the message queue.
248    */
249   GNUNET_SCHEDULER_TaskIdentifier transmission_task;
250
251   /**
252    * Tracker for inbound bandwidth.
253    */
254   struct GNUNET_BANDWIDTH_Tracker in_tracker;
255
256   /**
257    * Timestamp of the 'SESSION_CONNECT' message we got from the other peer
258    */
259   struct GNUNET_TIME_Absolute connect_ts;
260
261   /**
262    * How often has the other peer (recently) violated the inbound
263    * traffic limit?  Incremented by 10 per violation, decremented by 1
264    * per non-violation (for each time interval).
265    */
266   unsigned int quota_violation_count;
267
268   /**
269    * Number of values in 'ats' array.
270    */
271   //unsigned int ats_count;
272
273   /**
274    * Are we already in the process of disconnecting this neighbour?
275    */
276   int in_disconnect;
277
278   /**
279    * Do we currently consider this neighbour connected? (as far as
280    * the connect/disconnect callbacks are concerned)?
281    */
282   int is_connected;
283
284 };
285
286
287 /**
288  * All known neighbours and their HELLOs.
289  */
290 static struct GNUNET_CONTAINER_MultiHashMap *neighbours;
291
292 /**
293  * Closure for connect_notify_cb and disconnect_notify_cb
294  */
295 static void *callback_cls;
296
297 /**
298  * Function to call when we connected to a neighbour.
299  */
300 static GNUNET_TRANSPORT_NotifyConnect connect_notify_cb;
301
302 /**
303  * Function to call when we disconnected from a neighbour.
304  */
305 static GNUNET_TRANSPORT_NotifyDisconnect disconnect_notify_cb;
306
307 /**
308  * counter for connected neighbours
309  */
310 static int neighbours_connected;
311
312 /**
313  * Lookup a neighbour entry in the neighbours hash map.
314  *
315  * @param pid identity of the peer to look up
316  * @return the entry, NULL if there is no existing record
317  */
318 static struct NeighbourMapEntry *
319 lookup_neighbour (const struct GNUNET_PeerIdentity *pid)
320 {
321   return GNUNET_CONTAINER_multihashmap_get (neighbours, &pid->hashPubKey);
322 }
323
324
325 /**
326  * Task invoked to start a transmission to another peer.
327  *
328  * @param cls the 'struct NeighbourMapEntry'
329  * @param tc scheduler context
330  */
331 static void
332 transmission_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
333
334
335 /**
336  * We're done with our transmission attempt, continue processing.
337  *
338  * @param cls the 'struct MessageQueue' of the message
339  * @param receiver intended receiver
340  * @param success whether it worked or not
341  */
342 static void
343 transmit_send_continuation (void *cls,
344                             const struct GNUNET_PeerIdentity *receiver,
345                             int success)
346 {
347   struct MessageQueue *mq;
348   struct NeighbourMapEntry *n;
349
350   mq = cls;
351   n = mq->n;
352   if (NULL != n)
353   {
354     GNUNET_assert (n->is_active == mq);
355     n->is_active = NULL;
356     GNUNET_assert (n->transmission_task == GNUNET_SCHEDULER_NO_TASK);
357     n->transmission_task = GNUNET_SCHEDULER_add_now (&transmission_task, n);
358   }
359   if (NULL != mq->cont)
360     mq->cont (mq->cont_cls, success);
361   GNUNET_free (mq);
362 }
363
364
365 /**
366  * Check the ready list for the given neighbour and if a plugin is
367  * ready for transmission (and if we have a message), do so!
368  *
369  * @param n target peer for which to transmit
370  */
371 static void
372 try_transmission_to_peer (struct NeighbourMapEntry *n)
373 {
374   struct MessageQueue *mq;
375   struct GNUNET_TIME_Relative timeout;
376   ssize_t ret;
377   struct GNUNET_TRANSPORT_PluginFunctions *papi;
378
379   if (n->is_active != NULL)
380     return;                     /* transmission already pending */
381   if (n->transmission_task != GNUNET_SCHEDULER_NO_TASK)
382     return;                     /* currently waiting for bandwidth */
383   while (NULL != (mq = n->messages_head))
384   {
385     timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
386     if (timeout.rel_value > 0)
387       break;
388     GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
389     n->is_active = mq;
390     mq->n = n;
391     transmit_send_continuation (mq, &n->id, GNUNET_SYSERR);     /* timeout */
392   }
393   if (NULL == mq)
394     return;                     /* no more messages */
395
396   papi = GST_plugins_find (n->plugin_name);
397   if (papi == NULL)
398   {
399     GNUNET_break (0);
400     return;
401   }
402   GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
403   n->is_active = mq;
404   mq->n = n;
405
406   if  (((n->session == NULL) && (n->addr == NULL) && (n->addrlen == 0)))
407   {
408     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "No address for peer `%s'\n",
409                 GNUNET_i2s (&n->id));
410     transmit_send_continuation (mq, &n->id, GNUNET_SYSERR);
411     n->transmission_task = GNUNET_SCHEDULER_add_now (&transmission_task, n);
412     return;
413   }
414
415   ret =
416       papi->send (papi->cls, &n->id, mq->message_buf, mq->message_buf_size,
417                   0 /* priority -- remove from plugin API? */ ,
418                   timeout, n->session, n->addr, n->addrlen, GNUNET_YES,
419                   &transmit_send_continuation, mq);
420   if (ret == -1)
421   {
422     /* failure, but 'send' would not call continuation in this case,
423      * so we need to do it here! */
424     transmit_send_continuation (mq, &n->id, GNUNET_SYSERR);
425     n->transmission_task = GNUNET_SCHEDULER_add_now (&transmission_task, n);
426   }
427 }
428
429
430 /**
431  * Task invoked to start a transmission to another peer.
432  *
433  * @param cls the 'struct NeighbourMapEntry'
434  * @param tc scheduler context
435  */
436 static void
437 transmission_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
438 {
439   struct NeighbourMapEntry *n = cls;
440
441   n->transmission_task = GNUNET_SCHEDULER_NO_TASK;
442   try_transmission_to_peer (n);
443 }
444
445
446 /**
447  * Initialize the neighbours subsystem.
448  *
449  * @param cls closure for callbacks
450  * @param connect_cb function to call if we connect to a peer
451  * @param disconnect_cb function to call if we disconnect from a peer
452  */
453 void
454 GST_neighbours_start (void *cls, GNUNET_TRANSPORT_NotifyConnect connect_cb,
455                       GNUNET_TRANSPORT_NotifyDisconnect disconnect_cb)
456 {
457   callback_cls = cls;
458   connect_notify_cb = connect_cb;
459   disconnect_notify_cb = disconnect_cb;
460   neighbours = GNUNET_CONTAINER_multihashmap_create (NEIGHBOUR_TABLE_SIZE);
461 }
462
463
464 /**
465  * Disconnect from the given neighbour, clean up the record.
466  *
467  * @param n neighbour to disconnect from
468  */
469 static void
470 disconnect_neighbour (struct NeighbourMapEntry *n)
471 {
472   struct MessageQueue *mq;
473
474   if (GNUNET_YES == n->in_disconnect)
475     return;
476   n->in_disconnect = GNUNET_YES;
477   while (NULL != (mq = n->messages_head))
478   {
479     GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
480     if (NULL != mq->cont)
481       mq->cont (mq->cont_cls, GNUNET_SYSERR);
482     GNUNET_free (mq);
483   }
484   if (NULL != n->is_active)
485   {
486     n->is_active->n = NULL;
487     n->is_active = NULL;
488   }
489   if (GNUNET_YES == n->is_connected)
490   {
491     n->is_connected = GNUNET_NO;
492     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != n->keepalive_task);
493     GNUNET_SCHEDULER_cancel (n->keepalive_task);
494     n->keepalive_task = GNUNET_SCHEDULER_NO_TASK;  
495     GNUNET_assert (neighbours_connected > 0);
496     neighbours_connected--;
497     GNUNET_STATISTICS_update (GST_stats, gettext_noop ("# peers connected"), -1,
498                               GNUNET_NO);
499     disconnect_notify_cb (callback_cls, &n->id);
500   }
501   GNUNET_assert (GNUNET_YES ==
502                  GNUNET_CONTAINER_multihashmap_remove (neighbours,
503                                                        &n->id.hashPubKey, n));
504   if (GNUNET_SCHEDULER_NO_TASK != n->timeout_task)
505   {
506     GNUNET_SCHEDULER_cancel (n->timeout_task);
507     n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
508   }
509   if (GNUNET_SCHEDULER_NO_TASK != n->transmission_task)
510   {
511     GNUNET_SCHEDULER_cancel (n->transmission_task);
512     n->transmission_task = GNUNET_SCHEDULER_NO_TASK;
513   }
514   if (NULL != n->plugin_name)
515   {
516     GNUNET_free (n->plugin_name);
517     n->plugin_name = NULL;
518   }
519   if (NULL != n->addr)
520   {
521     GNUNET_free (n->addr);
522     n->addr = NULL;
523     n->addrlen = 0;
524   }
525   n->session = NULL;
526   GNUNET_free (n);
527 }
528
529
530 /**
531  * Peer has been idle for too long. Disconnect.
532  *
533  * @param cls the 'struct NeighbourMapEntry' of the neighbour that went idle
534  * @param tc scheduler context
535  */
536 static void
537 neighbour_timeout_task (void *cls,
538                         const struct GNUNET_SCHEDULER_TaskContext *tc)
539 {
540   struct NeighbourMapEntry *n = cls;
541
542   n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
543   if (GNUNET_YES == n->is_connected)
544     GNUNET_STATISTICS_update (GST_stats,
545                             gettext_noop ("# peers disconnected due to timeout"), 1,
546                             GNUNET_NO);
547   disconnect_neighbour (n);
548 }
549
550
551 /**
552  * Send another keepalive message.
553  *
554  * @param cls the 'struct NeighbourMapEntry' of the neighbour that went idle
555  * @param tc scheduler context
556  */
557 static void
558 neighbour_keepalive_task (void *cls,
559                           const struct GNUNET_SCHEDULER_TaskContext *tc)
560 {
561   struct NeighbourMapEntry *n = cls;
562   struct GNUNET_MessageHeader m;
563   struct GNUNET_TRANSPORT_PluginFunctions *papi;
564
565   n->keepalive_task = GNUNET_SCHEDULER_add_delayed (KEEPALIVE_FREQUENCY,
566                                                     &neighbour_keepalive_task,
567                                                     n);
568   GNUNET_assert (GNUNET_YES == n->is_connected);
569   GNUNET_STATISTICS_update (GST_stats,
570                             gettext_noop ("# keepalives sent"), 1,
571                             GNUNET_NO);
572   m.size = htons (sizeof (struct GNUNET_MessageHeader));
573   m.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE);
574   papi = GST_plugins_find (n->plugin_name);
575   if (papi != NULL)
576     papi->send (papi->cls, 
577                 &n->id, (const void *) &m,
578                 sizeof (m),
579                 UINT32_MAX /* priority */ ,
580                 GNUNET_TIME_UNIT_FOREVER_REL, n->session, n->addr, n->addrlen,
581                 GNUNET_YES, NULL, NULL);
582 }
583
584
585 /**
586  * Disconnect from the given neighbour.
587  *
588  * @param cls unused
589  * @param key hash of neighbour's public key (not used)
590  * @param value the 'struct NeighbourMapEntry' of the neighbour
591  */
592 static int
593 disconnect_all_neighbours (void *cls, const GNUNET_HashCode * key, void *value)
594 {
595   struct NeighbourMapEntry *n = value;
596
597 #if DEBUG_TRANSPORT
598   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting peer `%4s', %s\n",
599               GNUNET_i2s (&n->id), "SHUTDOWN_TASK");
600 #endif
601   if (GNUNET_YES == n->is_connected)
602     GNUNET_STATISTICS_update (GST_stats,
603                               gettext_noop ("# peers disconnected due to global disconnect"), 1,
604                               GNUNET_NO);
605   disconnect_neighbour (n);
606   return GNUNET_OK;
607 }
608
609
610 /**
611  * Cleanup the neighbours subsystem.
612  */
613 void
614 GST_neighbours_stop ()
615 {
616   GNUNET_assert (neighbours != NULL);
617
618   GNUNET_CONTAINER_multihashmap_iterate (neighbours, &disconnect_all_neighbours,
619                                          NULL);
620   GNUNET_CONTAINER_multihashmap_destroy (neighbours);
621   GNUNET_assert (neighbours_connected == 0);
622   neighbours = NULL;
623   callback_cls = NULL;
624   connect_notify_cb = NULL;
625   disconnect_notify_cb = NULL;
626 }
627
628
629 /**
630  * We tried to send a SESSION_CONNECT message to another peer.  If this
631  * succeeded, we should mark the peer up.  If it failed, we should tell
632  * ATS to not use this address anymore (until it is re-validated).
633  *
634  * @param cls the 'struct NeighbourMapEntry'
635  * @param success GNUNET_OK on success
636  */
637 static void
638 send_connect_continuation (void *cls,
639                            int success)
640 {
641   struct NeighbourMapEntry *n = cls;
642
643   if (GNUNET_YES == n->in_disconnect)
644     return; /* neighbour is going away */
645   if (GNUNET_YES != success)
646   {
647     GNUNET_ATS_address_destroyed (GST_ats,
648                                   &n->id,
649                                   n->plugin_name, 
650                                   n->addr,
651                                   n->addrlen,
652                                   NULL);
653     disconnect_neighbour (n);
654     return;
655   }
656 }
657
658
659 /**
660  * For an existing neighbour record, set the active connection to
661  * the given address.
662  *
663  * @param peer identity of the peer to switch the address for
664  * @param plugin_name name of transport that delivered the PONG
665  * @param address address of the other peer, NULL if other peer
666  *                       connected to us
667  * @param address_len number of bytes in address
668  * @param session session to use (or NULL)
669  * @param ats performance data
670  * @param ats_count number of entries in ats (excluding 0-termination)
671  * @return GNUNET_YES if we are currently connected, GNUNET_NO if the
672  *         connection is not up (yet)
673  */
674 int
675 GST_neighbours_switch_to_address (const struct GNUNET_PeerIdentity *peer,
676                                   const char *plugin_name, const void *address,
677                                   size_t address_len, struct Session *session,
678                                   const struct GNUNET_ATS_Information
679                                   *ats, uint32_t ats_count)
680 {
681   struct NeighbourMapEntry *n;
682   struct SessionConnectMessage connect_msg;
683   int was_connected;
684
685   GNUNET_assert (neighbours != NULL);
686   n = lookup_neighbour (peer);
687   if (NULL == n)
688   {
689     if (NULL == session)
690       GNUNET_ATS_address_destroyed (GST_ats,
691                                     peer,
692                                     plugin_name, address,
693                                     address_len, NULL);    
694     return GNUNET_NO;
695   }
696   was_connected = n->is_connected;
697   n->is_connected = GNUNET_YES;
698   if (GNUNET_YES != was_connected)
699     n->keepalive_task = GNUNET_SCHEDULER_add_delayed (KEEPALIVE_FREQUENCY,
700                                                       &neighbour_keepalive_task,
701                                                       n);
702
703 #if DEBUG_TRANSPORT
704   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
705               "SWITCH! Peer `%4s' switches to plugin `%s' address '%s' session %X\n",
706               GNUNET_i2s (peer), plugin_name,
707               (address_len == 0) ? "<inbound>" : GST_plugins_a2s (plugin_name,
708                                                                   address,
709                                                                   address_len),
710               session);
711 #endif
712   GNUNET_free_non_null (n->addr);
713   n->addr = GNUNET_malloc (address_len);
714   memcpy (n->addr, address, address_len);
715   n->addrlen = address_len;
716   n->session = session;
717   GNUNET_free_non_null (n->plugin_name);
718   n->plugin_name = GNUNET_strdup (plugin_name);
719   GNUNET_SCHEDULER_cancel (n->timeout_task);
720   n->timeout_task =
721       GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
722                                     &neighbour_timeout_task, n);
723   connect_msg.header.size = htons (sizeof (struct SessionConnectMessage));
724   connect_msg.header.type =
725       htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT);
726   connect_msg.reserved = htonl (0);
727   connect_msg.timestamp =
728       GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
729   GST_neighbours_send (peer, &connect_msg, sizeof (connect_msg),
730                        GNUNET_TIME_UNIT_FOREVER_REL, 
731                        &send_connect_continuation, 
732                        n);
733   if (GNUNET_YES == was_connected)
734     return GNUNET_YES;
735   /* First tell clients about connected neighbours...*/
736   neighbours_connected++;
737   GNUNET_STATISTICS_update (GST_stats, gettext_noop ("# peers connected"), 1,
738                             GNUNET_NO);
739   connect_notify_cb (callback_cls, peer, ats, ats_count);
740   return GNUNET_YES;
741 }
742
743
744 /**
745  * Create an entry in the neighbour map for the given peer
746  * 
747  * @param peer peer to create an entry for
748  * @return new neighbour map entry
749  */
750 static struct NeighbourMapEntry *
751 setup_neighbour (const struct GNUNET_PeerIdentity *peer)
752 {
753   struct NeighbourMapEntry *n;
754
755 #if DEBUG_TRANSPORT
756   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
757               "Unknown peer `%s', creating new neighbour\n",
758               GNUNET_i2s (peer));
759 #endif
760   n = GNUNET_malloc (sizeof (struct NeighbourMapEntry));
761   n->id = *peer;
762   GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
763                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
764                                  MAX_BANDWIDTH_CARRY_S);
765   n->timeout_task =
766     GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
767                                   &neighbour_timeout_task, n);
768   GNUNET_assert (GNUNET_OK ==
769                  GNUNET_CONTAINER_multihashmap_put (neighbours,
770                                                     &n->id.hashPubKey, n,
771                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
772   return n;
773 }
774
775
776 /**
777  * Try to create a connection to the given target (eventually).
778  *
779  * @param target peer to try to connect to
780  */
781 void
782 GST_neighbours_try_connect (const struct GNUNET_PeerIdentity *target)
783 {
784   struct NeighbourMapEntry *n;
785
786   GNUNET_assert (neighbours != NULL);
787 #if DEBUG_TRANSPORT
788   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Trying to connect to peer `%s'\n",
789               GNUNET_i2s (target));
790 #endif
791   GNUNET_assert (0 !=
792                  memcmp (target, &GST_my_identity,
793                          sizeof (struct GNUNET_PeerIdentity)));
794   n = lookup_neighbour (target);
795   if ((NULL != n) && (GNUNET_YES == n->is_connected))
796     return;                     /* already connected */
797   if (n == NULL)
798     n = setup_neighbour (target);
799 #if DEBUG_TRANSPORT
800   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
801               "Asking ATS for suggested address to connect to peer `%s'\n",
802               GNUNET_i2s (&n->id));
803 #endif
804    GNUNET_ATS_suggest_address (GST_ats, &n->id);
805 }
806
807
808 /**
809  * Test if we're connected to the given peer.
810  *
811  * @param target peer to test
812  * @return GNUNET_YES if we are connected, GNUNET_NO if not
813  */
814 int
815 GST_neighbours_test_connected (const struct GNUNET_PeerIdentity *target)
816 {
817   struct NeighbourMapEntry *n;
818
819   GNUNET_assert (neighbours != NULL);
820
821   n = lookup_neighbour (target);
822   if ((NULL == n) || (n->is_connected != GNUNET_YES))
823     return GNUNET_NO;           /* not connected */
824   return GNUNET_YES;
825 }
826
827
828 /**
829  * A session was terminated. Take note.
830  *
831  * @param peer identity of the peer where the session died
832  * @param session session that is gone
833  */
834 void
835 GST_neighbours_session_terminated (const struct GNUNET_PeerIdentity *peer,
836                                    struct Session *session)
837 {
838   struct NeighbourMapEntry *n;
839
840   GNUNET_assert (neighbours != NULL);
841
842 #if DEBUG_TRANSPORT
843   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
844               "Session %X to peer `%s' ended \n",
845               session, GNUNET_i2s (peer));
846 #endif
847   n = lookup_neighbour (peer);
848   if (NULL == n)
849     return;
850   if (session != n->session)
851     return;                     /* doesn't affect us */
852
853   n->session = NULL;
854   GNUNET_free (n->addr);
855   n->addr = NULL;
856   n->addrlen = 0;
857
858
859   if (GNUNET_YES != n->is_connected)
860     return;                     /* not connected anymore anyway, shouldn't matter */
861   /* fast disconnect unless ATS suggests a new address */
862   GNUNET_SCHEDULER_cancel (n->timeout_task);
863   n->timeout_task =
864       GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
865                                     &neighbour_timeout_task, n);
866   /* try QUICKLY to re-establish a connection, reduce timeout! */
867   GNUNET_ATS_suggest_address (GST_ats, peer);
868 }
869
870
871 /**
872  * Transmit a message to the given target using the active connection.
873  *
874  * @param target destination
875  * @param msg message to send
876  * @param msg_size number of bytes in msg
877  * @param timeout when to fail with timeout
878  * @param cont function to call when done
879  * @param cont_cls closure for 'cont'
880  */
881 void
882 GST_neighbours_send (const struct GNUNET_PeerIdentity *target, const void *msg,
883                      size_t msg_size, struct GNUNET_TIME_Relative timeout,
884                      GST_NeighbourSendContinuation cont, void *cont_cls)
885 {
886   struct NeighbourMapEntry *n;
887   struct MessageQueue *mq;
888
889   GNUNET_assert (neighbours != NULL);
890
891   n = lookup_neighbour (target);
892   if ((n == NULL) || (GNUNET_YES != n->is_connected))
893   {
894     GNUNET_STATISTICS_update (GST_stats,
895                               gettext_noop
896                               ("# messages not sent (no such peer or not connected)"),
897                               1, GNUNET_NO);
898 #if DEBUG_TRANSPORT
899     if (n == NULL)
900       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
901                   "Could not send message to peer `%s': unknown neighbor",
902                   GNUNET_i2s (target));
903     else if (GNUNET_YES != n->is_connected)
904       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
905                   "Could not send message to peer `%s': not connected\n",
906                   GNUNET_i2s (target));
907 #endif
908     if (NULL != cont)
909       cont (cont_cls, GNUNET_SYSERR);
910     return;
911   }
912
913   if ((n->session == NULL) && (n->addr == NULL) && (n->addrlen ==0))
914   {
915     GNUNET_STATISTICS_update (GST_stats,
916                               gettext_noop
917                               ("# messages not sent (no such peer or not connected)"),
918                               1, GNUNET_NO);
919 #if DEBUG_TRANSPORT
920       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
921                   "Could not send message to peer `%s': no address available\n",
922                   GNUNET_i2s (target));
923 #endif
924
925     if (NULL != cont)
926       cont (cont_cls, GNUNET_SYSERR);
927     return;
928   }
929   GNUNET_assert (msg_size >= sizeof (struct GNUNET_MessageHeader));
930   GNUNET_STATISTICS_update (GST_stats,
931                             gettext_noop
932                             ("# bytes in message queue for other peers"),
933                             msg_size, GNUNET_NO);
934   mq = GNUNET_malloc (sizeof (struct MessageQueue) + msg_size);
935   mq->cont = cont;
936   mq->cont_cls = cont_cls;
937   /* FIXME: this memcpy can be up to 7% of our total runtime! */
938   memcpy (&mq[1], msg, msg_size);
939   mq->message_buf = (const char *) &mq[1];
940   mq->message_buf_size = msg_size;
941   mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
942   GNUNET_CONTAINER_DLL_insert_tail (n->messages_head, n->messages_tail, mq);
943   if ((GNUNET_SCHEDULER_NO_TASK == n->transmission_task) &&
944       (NULL == n->is_active))
945     n->transmission_task = GNUNET_SCHEDULER_add_now (&transmission_task, n);
946 }
947
948
949 /**
950  * We have received a message from the given sender.  How long should
951  * we delay before receiving more?  (Also used to keep the peer marked
952  * as live).
953  *
954  * @param sender sender of the message
955  * @param size size of the message
956  * @param do_forward set to GNUNET_YES if the message should be forwarded to clients
957  *                   GNUNET_NO if the neighbour is not connected or violates the quota,
958  *                   GNUNET_SYSERR if the connection is not fully up yet
959  * @return how long to wait before reading more from this sender
960  */
961 struct GNUNET_TIME_Relative
962 GST_neighbours_calculate_receive_delay (const struct GNUNET_PeerIdentity
963                                         *sender, ssize_t size, int *do_forward)
964 {
965   struct NeighbourMapEntry *n;
966   struct GNUNET_TIME_Relative ret;
967
968   GNUNET_assert (neighbours != NULL);
969
970   n = lookup_neighbour (sender);
971   if (n == NULL)
972   {
973     GST_neighbours_try_connect (sender);
974     n = lookup_neighbour (sender);
975     if (NULL == n)
976     {
977       GNUNET_STATISTICS_update (GST_stats,
978                                 gettext_noop
979                                 ("# messages discarded due to lack of neighbour record"),
980                                 1, GNUNET_NO);
981       *do_forward = GNUNET_NO;
982       return GNUNET_TIME_UNIT_ZERO;
983     }
984   }
985   if (GNUNET_YES != n->is_connected)
986   {
987     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
988                 _("Plugin gave us %d bytes of data but somehow the session is not marked as UP yet!\n"),
989                 (int) size);
990     *do_forward = GNUNET_SYSERR;
991     return GNUNET_TIME_UNIT_ZERO;
992   }
993   if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, size))
994   {
995     n->quota_violation_count++;
996 #if DEBUG_TRANSPORT
997     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
998                 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
999                 n->in_tracker.available_bytes_per_s__,
1000                 n->quota_violation_count);
1001 #endif
1002     /* Discount 32k per violation */
1003     GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, -32 * 1024);
1004   }
1005   else
1006   {
1007     if (n->quota_violation_count > 0)
1008     {
1009       /* try to add 32k back */
1010       GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, 32 * 1024);
1011       n->quota_violation_count--;
1012     }
1013   }
1014   if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
1015   {
1016     GNUNET_STATISTICS_update (GST_stats,
1017                               gettext_noop
1018                               ("# bandwidth quota violations by other peers"),
1019                               1, GNUNET_NO);
1020     *do_forward = GNUNET_NO;
1021     return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
1022   }
1023   *do_forward = GNUNET_YES;
1024   ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 32 * 1024);
1025   if (ret.rel_value > 0)
1026   {
1027 #if DEBUG_TRANSPORT
1028     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1029                 "Throttling read (%llu bytes excess at %u b/s), waiting %llu ms before reading more.\n",
1030                 (unsigned long long) n->in_tracker.
1031                 consumption_since_last_update__,
1032                 (unsigned int) n->in_tracker.available_bytes_per_s__,
1033                 (unsigned long long) ret.rel_value);
1034 #endif
1035     GNUNET_STATISTICS_update (GST_stats,
1036                               gettext_noop ("# ms throttling suggested"),
1037                               (int64_t) ret.rel_value, GNUNET_NO);
1038   }
1039   return ret;
1040 }
1041
1042
1043 /**
1044  * Keep the connection to the given neighbour alive longer,
1045  * we received a KEEPALIVE (or equivalent).
1046  *
1047  * @param neighbour neighbour to keep alive
1048  */
1049 void
1050 GST_neighbours_keepalive (const struct GNUNET_PeerIdentity *neighbour)
1051 {
1052   struct NeighbourMapEntry *n;
1053
1054   GNUNET_assert (neighbours != NULL);
1055
1056   n = lookup_neighbour (neighbour);
1057   if (NULL == n)
1058   {
1059     GNUNET_STATISTICS_update (GST_stats,
1060                               gettext_noop
1061                               ("# KEEPALIVE messages discarded (not connected)"),
1062                               1, GNUNET_NO);
1063     return;
1064   }
1065   GNUNET_SCHEDULER_cancel (n->timeout_task);
1066   n->timeout_task =
1067       GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1068                                     &neighbour_timeout_task, n);
1069 }
1070
1071
1072 /**
1073  * Change the incoming quota for the given peer.
1074  *
1075  * @param neighbour identity of peer to change qutoa for
1076  * @param quota new quota
1077  */
1078 void
1079 GST_neighbours_set_incoming_quota (const struct GNUNET_PeerIdentity *neighbour,
1080                                    struct GNUNET_BANDWIDTH_Value32NBO quota)
1081 {
1082   struct NeighbourMapEntry *n;
1083
1084   GNUNET_assert (neighbours != NULL);
1085
1086   n = lookup_neighbour (neighbour);
1087   if (n == NULL)
1088   {
1089     GNUNET_STATISTICS_update (GST_stats,
1090                               gettext_noop
1091                               ("# SET QUOTA messages ignored (no such peer)"),
1092                               1, GNUNET_NO);
1093     return;
1094   }
1095   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker, quota);
1096   if (0 != ntohl (quota.value__))
1097     return;
1098 #if DEBUG_TRANSPORT
1099   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting peer `%4s' due to `%s'\n",
1100               GNUNET_i2s (&n->id), "SET_QUOTA");
1101 #endif
1102   if (GNUNET_YES == n->is_connected)
1103     GNUNET_STATISTICS_update (GST_stats,
1104                               gettext_noop ("# disconnects due to quota of 0"), 1,
1105                               GNUNET_NO);
1106   disconnect_neighbour (n);
1107 }
1108
1109
1110 /**
1111  * Closure for the neighbours_iterate function.
1112  */
1113 struct IteratorContext
1114 {
1115   /**
1116    * Function to call on each connected neighbour.
1117    */
1118   GST_NeighbourIterator cb;
1119
1120   /**
1121    * Closure for 'cb'.
1122    */
1123   void *cb_cls;
1124 };
1125
1126
1127 /**
1128  * Call the callback from the closure for each connected neighbour.
1129  *
1130  * @param cls the 'struct IteratorContext'
1131  * @param key the hash of the public key of the neighbour
1132  * @param value the 'struct NeighbourMapEntry'
1133  * @return GNUNET_OK (continue to iterate)
1134  */
1135 static int
1136 neighbours_iterate (void *cls, const GNUNET_HashCode * key, void *value)
1137 {
1138   struct IteratorContext *ic = cls;
1139   struct NeighbourMapEntry *n = value;
1140
1141   if (GNUNET_YES != n->is_connected)
1142     return GNUNET_OK;
1143
1144   ic->cb (ic->cb_cls, &n->id, NULL, 0, n->plugin_name, n->addr, n->addrlen);
1145   return GNUNET_OK;
1146 }
1147
1148
1149 /**
1150  * Iterate over all connected neighbours.
1151  *
1152  * @param cb function to call
1153  * @param cb_cls closure for cb
1154  */
1155 void
1156 GST_neighbours_iterate (GST_NeighbourIterator cb, void *cb_cls)
1157 {
1158   struct IteratorContext ic;
1159
1160   GNUNET_assert (neighbours != NULL);
1161
1162   ic.cb = cb;
1163   ic.cb_cls = cb_cls;
1164   GNUNET_CONTAINER_multihashmap_iterate (neighbours, &neighbours_iterate, &ic);
1165 }
1166
1167
1168 /**
1169  * If we have an active connection to the given target, it must be shutdown.
1170  *
1171  * @param target peer to disconnect from
1172  */
1173 void
1174 GST_neighbours_force_disconnect (const struct GNUNET_PeerIdentity *target)
1175 {
1176   struct NeighbourMapEntry *n;
1177   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1178   struct SessionDisconnectMessage disconnect_msg;
1179
1180   GNUNET_assert (neighbours != NULL);
1181
1182   n = lookup_neighbour (target);
1183   if (NULL == n)
1184     return;                     /* not active */
1185   if (GNUNET_YES == n->is_connected)
1186   {
1187     /* we're actually connected, send DISCONNECT message */
1188     disconnect_msg.header.size = htons (sizeof (struct SessionDisconnectMessage));
1189     disconnect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
1190     disconnect_msg.reserved = htonl (0);
1191     disconnect_msg.purpose.size = htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
1192                                          sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
1193                                          sizeof (struct GNUNET_TIME_AbsoluteNBO) );
1194     disconnect_msg.purpose.purpose = htonl (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT);
1195     disconnect_msg.timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1196     disconnect_msg.public_key = GST_my_public_key;
1197     GNUNET_assert (GNUNET_OK ==
1198                    GNUNET_CRYPTO_rsa_sign (GST_my_private_key,
1199                                            &disconnect_msg.purpose,
1200                                            &disconnect_msg.signature));
1201     papi = GST_plugins_find (n->plugin_name);
1202     if (papi != NULL)
1203       papi->send (papi->cls, target, (const void *) &disconnect_msg,
1204                   sizeof (disconnect_msg),
1205                   UINT32_MAX /* priority */ ,
1206                   GNUNET_TIME_UNIT_FOREVER_REL, n->session, n->addr, n->addrlen,
1207                   GNUNET_YES, NULL, NULL);
1208     GNUNET_STATISTICS_update (GST_stats,
1209                               gettext_noop ("# peers disconnected due to external request"), 1,
1210                               GNUNET_NO);
1211     n = lookup_neighbour (target);
1212     if (NULL == n)
1213       return;                     /* gone already */
1214   }
1215   disconnect_neighbour (n);
1216 }
1217
1218
1219 /**
1220  * We received a disconnect message from the given peer,
1221  * validate and process.
1222  * 
1223  * @param peer sender of the message
1224  * @param msg the disconnect message
1225  */
1226 void
1227 GST_neighbours_handle_disconnect_message (const struct GNUNET_PeerIdentity *peer,
1228                                           const struct GNUNET_MessageHeader *msg)
1229 {
1230   struct NeighbourMapEntry *n;
1231   const struct SessionDisconnectMessage *sdm;
1232   GNUNET_HashCode hc;
1233
1234   if (ntohs (msg->size) != sizeof (struct SessionDisconnectMessage))
1235   {
1236     // GNUNET_break_op (0);
1237     GNUNET_STATISTICS_update (GST_stats,
1238                               gettext_noop ("# disconnect messages ignored (old format)"), 1,
1239                               GNUNET_NO);
1240     return;
1241   }
1242   sdm = (const struct SessionDisconnectMessage* ) msg;
1243   n = lookup_neighbour (peer);
1244   if (NULL == n)
1245     return;                     /* gone already */
1246   if (GNUNET_TIME_absolute_ntoh (sdm->timestamp).abs_value <=
1247       n->connect_ts.abs_value)
1248   {
1249     GNUNET_STATISTICS_update (GST_stats,
1250                               gettext_noop ("# disconnect messages ignored (timestamp)"), 1,
1251                               GNUNET_NO);
1252     return;
1253   }
1254   GNUNET_CRYPTO_hash (&sdm->public_key,
1255                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1256                       &hc);
1257   if (0 != memcmp (peer,
1258                    &hc,
1259                    sizeof (struct GNUNET_PeerIdentity)))
1260   {
1261     GNUNET_break_op (0);
1262     return;
1263   }
1264   if (ntohl (sdm->purpose.size) != 
1265       sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
1266       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
1267       sizeof (struct GNUNET_TIME_AbsoluteNBO))
1268   {
1269     GNUNET_break_op (0);
1270     return;
1271   }
1272   if (GNUNET_OK !=
1273       GNUNET_CRYPTO_rsa_verify (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT,
1274                                 &sdm->purpose,
1275                                 &sdm->signature,
1276                                 &sdm->public_key))
1277   {
1278     GNUNET_break_op (0);
1279     return;
1280   }
1281   GST_neighbours_force_disconnect (peer);
1282 }
1283
1284
1285 /**
1286  * We received a 'SESSION_CONNECT' message from the other peer.
1287  * Consider switching to it.
1288  *
1289  * @param message possibly a 'struct SessionConnectMessage' (check format)
1290  * @param peer identity of the peer to switch the address for
1291  * @param plugin_name name of transport that delivered the PONG
1292  * @param address address of the other peer, NULL if other peer
1293  *                       connected to us
1294  * @param address_len number of bytes in address
1295  * @param session session to use (or NULL)
1296  * @param ats performance data
1297  * @param ats_count number of entries in ats (excluding 0-termination)
1298   */
1299 void
1300 GST_neighbours_handle_connect (const struct GNUNET_MessageHeader *message,
1301                                const struct GNUNET_PeerIdentity *peer,
1302                                const char *plugin_name,
1303                                const char *sender_address, uint16_t sender_address_len,
1304                                struct Session *session,
1305                                const struct GNUNET_ATS_Information *ats,
1306                                uint32_t ats_count)
1307 {
1308   const struct SessionConnectMessage *scm;
1309   struct GNUNET_TIME_Absolute ts;
1310   struct NeighbourMapEntry *n;
1311
1312   if (ntohs (message->size) != sizeof (struct SessionConnectMessage))
1313   {
1314     GNUNET_break_op (0);
1315     return;
1316   }
1317   scm = (const struct SessionConnectMessage *) message;
1318   GNUNET_break_op (ntohl (scm->reserved) == 0);
1319   ts = GNUNET_TIME_absolute_ntoh (scm->timestamp);
1320   n = lookup_neighbour (peer);
1321   if (NULL == n) 
1322     n = setup_neighbour (peer);
1323   if (ts.abs_value > n->connect_ts.abs_value)
1324   {
1325     if (NULL != session)
1326       GNUNET_log_from (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
1327                        "transport-ats",
1328                        "Giving ATS session %p of plugin %s for peer %s\n",
1329                        session,
1330                        plugin_name,
1331                        GNUNET_i2s (peer));
1332     GNUNET_ATS_address_update (GST_ats,
1333                                peer,
1334                                plugin_name, sender_address, sender_address_len,
1335                                session, ats, ats_count);
1336     n->connect_ts = ts;
1337   }
1338 }
1339
1340
1341 /* end of file gnunet-service-transport_neighbours.c */