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