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