indentation
[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->transmission_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 =
586       htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT);
587   connect_msg.reserved = htonl (0);
588   connect_msg.timestamp =
589       GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
590   GST_neighbours_send (peer, &connect_msg, sizeof (connect_msg),
591                        GNUNET_TIME_UNIT_FOREVER_REL, NULL, NULL);
592 }
593
594
595 /**
596  * Try to connect to the target peer using the given address
597  *
598  * @param cls the 'struct NeighbourMapEntry' of the target
599  * @param target identity of the target peer
600  * @param plugin_name name of the plugin
601  * @param plugin_address binary address
602  * @param plugin_address_len length of address
603  * @param session session to use
604  * @param bandwidth available bandwidth
605  * @param ats performance data for the address (as far as known)
606  * @param ats_count number of performance records in 'ats'
607  */
608 static void
609 try_connect_using_address (void *cls, const struct GNUNET_PeerIdentity *target,
610                            const char *plugin_name, const void *plugin_address,
611                            size_t plugin_address_len, struct Session *session,
612                            struct GNUNET_BANDWIDTH_Value32NBO bandwidth,
613                            const struct GNUNET_TRANSPORT_ATS_Information *ats,
614                            uint32_t ats_count)
615 {
616   struct NeighbourMapEntry *n = cls;
617   int was_connected;
618
619   n->asc = NULL;
620   was_connected = n->is_connected;
621   n->is_connected = GNUNET_YES;
622   GST_neighbours_switch_to_address (target, plugin_name, plugin_address,
623                                     plugin_address_len, session, ats,
624                                     ats_count);
625   if (GNUNET_YES == was_connected)
626     return;
627
628   neighbours_connected++;
629   GNUNET_STATISTICS_update (GST_stats, gettext_noop ("# peers connected"), 1,
630                             GNUNET_NO);
631   connect_notify_cb (callback_cls, target, n->ats, n->ats_count);
632 }
633
634
635 /**
636  * Try to create a connection to the given target (eventually).
637  *
638  * @param target peer to try to connect to
639  */
640 void
641 GST_neighbours_try_connect (const struct GNUNET_PeerIdentity *target)
642 {
643   struct NeighbourMapEntry *n;
644
645   GNUNET_assert (neighbours != NULL);
646
647 #if DEBUG_TRANSPORT
648   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Trying to connect to peer `%s'\n",
649               GNUNET_i2s (target));
650 #endif
651
652   GNUNET_assert (0 !=
653                  memcmp (target, &GST_my_identity,
654                          sizeof (struct GNUNET_PeerIdentity)));
655   n = lookup_neighbour (target);
656   if ((NULL != n) && (GNUNET_YES == n->is_connected))
657     return;                     /* already connected */
658   if (n == NULL)
659   {
660 #if DEBUG_TRANSPORT
661     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
662                 "Unknown peer `%s', creating new neighbour\n",
663                 GNUNET_i2s (target));
664 #endif
665     n = GNUNET_malloc (sizeof (struct NeighbourMapEntry));
666     n->id = *target;
667     GNUNET_array_grow (n->ats, n->ats_count, 1);
668     n->ats[0].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);;
669     n->ats[0].value = htonl (0);
670     GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
671                                    GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
672                                    MAX_BANDWIDTH_CARRY_S);
673     n->timeout_task =
674         GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
675                                       &neighbour_timeout_task, n);
676     GNUNET_assert (GNUNET_OK ==
677                    GNUNET_CONTAINER_multihashmap_put (neighbours,
678                                                       &n->id.hashPubKey, n,
679                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
680   }
681   if (n->asc != NULL)
682     return;                     /* already trying */
683 #if DEBUG_TRANSPORT
684   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
685               "Asking ATS for suggested address to connect to peer `%s'\n",
686               GNUNET_i2s (target));
687 #endif
688   n->asc =
689       GNUNET_ATS_suggest_address (GST_ats, target, &try_connect_using_address,
690                                   n);
691 }
692
693
694 /**
695  * Test if we're connected to the given peer.
696  *
697  * @param target peer to test
698  * @return GNUNET_YES if we are connected, GNUNET_NO if not
699  */
700 int
701 GST_neighbours_test_connected (const struct GNUNET_PeerIdentity *target)
702 {
703   struct NeighbourMapEntry *n;
704
705   GNUNET_assert (neighbours != NULL);
706
707   n = lookup_neighbour (target);
708   if ((NULL == n) || (n->is_connected != GNUNET_YES))
709     return GNUNET_NO;           /* not connected */
710   return GNUNET_YES;
711 }
712
713
714 /**
715  * A session was terminated. Take note.
716  *
717  * @param peer identity of the peer where the session died
718  * @param session session that is gone
719  */
720 void
721 GST_neighbours_session_terminated (const struct GNUNET_PeerIdentity *peer,
722                                    struct Session *session)
723 {
724   struct NeighbourMapEntry *n;
725
726   GNUNET_assert (neighbours != NULL);
727
728   n = lookup_neighbour (peer);
729   if (NULL == n)
730     return;
731   if (session != n->session)
732     return;                     /* doesn't affect us */
733   n->session = NULL;
734   if (GNUNET_YES != n->is_connected)
735     return;                     /* not connected anymore anyway, shouldn't matter */
736
737   GNUNET_SCHEDULER_cancel (n->timeout_task);
738   n->timeout_task =
739       GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
740                                     &neighbour_timeout_task, n);
741   /* try QUICKLY to re-establish a connection, reduce timeout! */
742   if (NULL != n->ats)
743   {
744     /* how can this be!? */
745     //GNUNET_break (0);
746     return;
747   }
748   n->asc =
749       GNUNET_ATS_suggest_address (GST_ats, peer, &try_connect_using_address, n);
750 }
751
752
753 /**
754  * Transmit a message to the given target using the active connection.
755  *
756  * @param target destination
757  * @param msg message to send
758  * @param msg_size number of bytes in msg
759  * @param timeout when to fail with timeout
760  * @param cont function to call when done
761  * @param cont_cls closure for 'cont'
762  */
763 void
764 GST_neighbours_send (const struct GNUNET_PeerIdentity *target, const void *msg,
765                      size_t msg_size, struct GNUNET_TIME_Relative timeout,
766                      GST_NeighbourSendContinuation cont, void *cont_cls)
767 {
768   struct NeighbourMapEntry *n;
769   struct MessageQueue *mq;
770
771   GNUNET_assert (neighbours != NULL);
772
773   n = lookup_neighbour (target);
774   if ((n == NULL) || (GNUNET_YES != n->is_connected))
775   {
776     GNUNET_STATISTICS_update (GST_stats,
777                               gettext_noop
778                               ("# messages not sent (no such peer or not connected)"),
779                               1, GNUNET_NO);
780 #if DEBUG_TRANSPORT
781     if (n == NULL)
782       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
783                   "Could not send message to peer `%s': unknown neighbor",
784                   GNUNET_i2s (target));
785     if (GNUNET_YES != n->is_connected)
786       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
787                   "Could not send message to peer `%s': not connected\n",
788                   GNUNET_i2s (target));
789 #endif
790     if (NULL != cont)
791       cont (cont_cls, GNUNET_SYSERR);
792     return;
793   }
794
795   GNUNET_assert (msg_size >= sizeof (struct GNUNET_MessageHeader));
796   GNUNET_STATISTICS_update (GST_stats,
797                             gettext_noop
798                             ("# bytes in message queue for other peers"),
799                             msg_size, GNUNET_NO);
800   mq = GNUNET_malloc (sizeof (struct MessageQueue) + msg_size);
801   mq->cont = cont;
802   mq->cont_cls = cont_cls;
803   /* FIXME: this memcpy can be up to 7% of our total runtime! */
804   memcpy (&mq[1], msg, msg_size);
805   mq->message_buf = (const char *) &mq[1];
806   mq->message_buf_size = msg_size;
807   mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
808   GNUNET_CONTAINER_DLL_insert_tail (n->messages_head, n->messages_tail, mq);
809   if ((GNUNET_SCHEDULER_NO_TASK == n->transmission_task) &&
810       (NULL == n->is_active))
811     n->transmission_task = GNUNET_SCHEDULER_add_now (&transmission_task, n);
812 }
813
814
815 /**
816  * We have received a message from the given sender.  How long should
817  * we delay before receiving more?  (Also used to keep the peer marked
818  * as live).
819  *
820  * @param sender sender of the message
821  * @param size size of the message
822  * @param do_forward set to GNUNET_YES if the message should be forwarded to clients
823  *                   GNUNET_NO if the neighbour is not connected or violates the quota
824  * @return how long to wait before reading more from this sender
825  */
826 struct GNUNET_TIME_Relative
827 GST_neighbours_calculate_receive_delay (const struct GNUNET_PeerIdentity
828                                         *sender, ssize_t size, int *do_forward)
829 {
830   struct NeighbourMapEntry *n;
831   struct GNUNET_TIME_Relative ret;
832
833   GNUNET_assert (neighbours != NULL);
834
835   n = lookup_neighbour (sender);
836   if (n == NULL)
837   {
838     *do_forward = GNUNET_NO;
839     return GNUNET_TIME_UNIT_ZERO;
840   }
841   if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, size))
842   {
843     n->quota_violation_count++;
844 #if DEBUG_TRANSPORT
845     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
846                 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
847                 n->in_tracker.available_bytes_per_s__,
848                 n->quota_violation_count);
849 #endif
850     /* Discount 32k per violation */
851     GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, -32 * 1024);
852   }
853   else
854   {
855     if (n->quota_violation_count > 0)
856     {
857       /* try to add 32k back */
858       GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, 32 * 1024);
859       n->quota_violation_count--;
860     }
861   }
862   if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
863   {
864     GNUNET_STATISTICS_update (GST_stats,
865                               gettext_noop
866                               ("# bandwidth quota violations by other peers"),
867                               1, GNUNET_NO);
868     *do_forward = GNUNET_NO;
869     return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
870   }
871   *do_forward = GNUNET_YES;
872   ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
873   if (ret.rel_value > 0)
874   {
875 #if DEBUG_TRANSPORT
876     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
877                 "Throttling read (%llu bytes excess at %u b/s), waiting %llu ms before reading more.\n",
878                 (unsigned long long) n->in_tracker.
879                 consumption_since_last_update__,
880                 (unsigned int) n->in_tracker.available_bytes_per_s__,
881                 (unsigned long long) ret.rel_value);
882 #endif
883     GNUNET_STATISTICS_update (GST_stats,
884                               gettext_noop ("# ms throttling suggested"),
885                               (int64_t) ret.rel_value, GNUNET_NO);
886   }
887   return ret;
888 }
889
890
891 /**
892  * Keep the connection to the given neighbour alive longer,
893  * we received a KEEPALIVE (or equivalent).
894  *
895  * @param neighbour neighbour to keep alive
896  */
897 void
898 GST_neighbours_keepalive (const struct GNUNET_PeerIdentity *neighbour)
899 {
900   struct NeighbourMapEntry *n;
901
902   GNUNET_assert (neighbours != NULL);
903
904   n = lookup_neighbour (neighbour);
905   if (NULL == n)
906   {
907     GNUNET_STATISTICS_update (GST_stats,
908                               gettext_noop
909                               ("# KEEPALIVE messages discarded (not connected)"),
910                               1, GNUNET_NO);
911     return;
912   }
913   GNUNET_SCHEDULER_cancel (n->timeout_task);
914   n->timeout_task =
915       GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
916                                     &neighbour_timeout_task, n);
917 }
918
919
920 /**
921  * Change the incoming quota for the given peer.
922  *
923  * @param neighbour identity of peer to change qutoa for
924  * @param quota new quota
925  */
926 void
927 GST_neighbours_set_incoming_quota (const struct GNUNET_PeerIdentity *neighbour,
928                                    struct GNUNET_BANDWIDTH_Value32NBO quota)
929 {
930   struct NeighbourMapEntry *n;
931
932   GNUNET_assert (neighbours != NULL);
933
934   n = lookup_neighbour (neighbour);
935   if (n == NULL)
936   {
937     GNUNET_STATISTICS_update (GST_stats,
938                               gettext_noop
939                               ("# SET QUOTA messages ignored (no such peer)"),
940                               1, GNUNET_NO);
941     return;
942   }
943   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker, quota);
944   if (0 != ntohl (quota.value__))
945     return;
946 #if DEBUG_TRANSPORT
947   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting peer `%4s' due to `%s'\n",
948               GNUNET_i2s (&n->id), "SET_QUOTA");
949 #endif
950   GNUNET_STATISTICS_update (GST_stats,
951                             gettext_noop ("# disconnects due to quota of 0"), 1,
952                             GNUNET_NO);
953   disconnect_neighbour (n);
954 }
955
956
957 /**
958  * Closure for the neighbours_iterate function.
959  */
960 struct IteratorContext
961 {
962   /**
963    * Function to call on each connected neighbour.
964    */
965   GST_NeighbourIterator cb;
966
967   /**
968    * Closure for 'cb'.
969    */
970   void *cb_cls;
971 };
972
973
974 /**
975  * Call the callback from the closure for each connected neighbour.
976  *
977  * @param cls the 'struct IteratorContext'
978  * @param key the hash of the public key of the neighbour
979  * @param value the 'struct NeighbourMapEntry'
980  * @return GNUNET_OK (continue to iterate)
981  */
982 static int
983 neighbours_iterate (void *cls, const GNUNET_HashCode * key, void *value)
984 {
985   struct IteratorContext *ic = cls;
986   struct NeighbourMapEntry *n = value;
987
988   if (GNUNET_YES != n->is_connected)
989     return GNUNET_OK;
990
991   GNUNET_assert (n->ats_count > 0);
992   ic->cb (ic->cb_cls, &n->id, n->ats, n->ats_count);
993   return GNUNET_OK;
994 }
995
996
997 /**
998  * Iterate over all connected neighbours.
999  *
1000  * @param cb function to call
1001  * @param cb_cls closure for cb
1002  */
1003 void
1004 GST_neighbours_iterate (GST_NeighbourIterator cb, void *cb_cls)
1005 {
1006   struct IteratorContext ic;
1007
1008   GNUNET_assert (neighbours != NULL);
1009
1010   ic.cb = cb;
1011   ic.cb_cls = cb_cls;
1012   GNUNET_CONTAINER_multihashmap_iterate (neighbours, &neighbours_iterate, &ic);
1013 }
1014
1015
1016 /**
1017  * If we have an active connection to the given target, it must be shutdown.
1018  *
1019  * @param target peer to disconnect from
1020  */
1021 void
1022 GST_neighbours_force_disconnect (const struct GNUNET_PeerIdentity *target)
1023 {
1024   struct NeighbourMapEntry *n;
1025   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1026   struct GNUNET_MessageHeader disconnect_msg;
1027
1028   GNUNET_assert (neighbours != NULL);
1029
1030   n = lookup_neighbour (target);
1031   if (NULL == n)
1032     return;                     /* not active */
1033   if (GNUNET_YES == n->is_connected)
1034   {
1035     /* we're actually connected, send DISCONNECT message */
1036     disconnect_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
1037     disconnect_msg.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
1038     papi = GST_plugins_find (n->plugin_name);
1039     if (papi != NULL)
1040       papi->send (papi->cls, target, (const void *) &disconnect_msg,
1041                   sizeof (struct GNUNET_MessageHeader),
1042                   UINT32_MAX /* priority */ ,
1043                   GNUNET_TIME_UNIT_FOREVER_REL, n->session, n->addr, n->addrlen,
1044                   GNUNET_YES, NULL, NULL);
1045   }
1046   disconnect_neighbour (n);
1047 }
1048
1049
1050 /* end of file gnunet-service-transport_neighbours.c */