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