finishing neighbours
[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 /**
231  * Lookup a neighbour entry in the neighbours hash map.
232  *
233  * @param pid identity of the peer to look up
234  * @return the entry, NULL if there is no existing record
235  */
236 static struct NeighbourMapEntry *
237 lookup_neighbour (const struct GNUNET_PeerIdentity *pid)
238 {
239   return GNUNET_CONTAINER_multihashmap_get (neighbours,
240                                             &pid->hashPubKey);
241 }
242
243
244 /**
245  * Task invoked to start a transmission to another peer.
246  *
247  * @param cls the 'struct NeighbourMapEntry'
248  * @param tc scheduler context
249  */
250 static void
251 transmission_task (void *cls,
252                    const struct GNUNET_SCHEDULER_TaskContext *tc);
253
254
255 /**
256  * We're done with our transmission attempt, continue processing.
257  *
258  * @param cls the 'struct MessageQueue' of the message
259  * @param receiver intended receiver
260  * @param success whether it worked or not
261  */
262 static void
263 transmit_send_continuation (void *cls,
264                             const struct GNUNET_PeerIdentity *receiver,
265                             int success)
266 {
267   struct MessageQueue *mq;
268   struct NeighbourMapEntry *n;
269   
270   mq = cls;
271   n = mq->n;
272   if (NULL != n) 
273     {
274       GNUNET_assert (n->is_active == mq);
275       n->is_active = NULL;
276       GNUNET_assert (n->transmission_task == GNUNET_SCHEDULER_NO_TASK);
277       n->transmission_task = GNUNET_SCHEDULER_add_now (&transmission_task,
278                                                        n);
279     }
280   if (NULL != mq->cont)
281     mq->cont (mq->cont_cls,
282               success);
283   GNUNET_free (mq);
284 }
285
286
287 /**
288  * Check the ready list for the given neighbour and if a plugin is
289  * ready for transmission (and if we have a message), do so!
290  *
291  * @param neighbour target peer for which to transmit
292  */
293 static void
294 try_transmission_to_peer (struct NeighbourMapEntry *n)
295 {
296   struct MessageQueue *mq;
297   struct GNUNET_TIME_Relative timeout;
298   ssize_t ret;
299   struct GNUNET_TRANSPORT_PluginFunctions *papi;
300
301   if (n->is_active != NULL)
302     return; /* transmission already pending */
303   if (n->transmission_task != GNUNET_SCHEDULER_NO_TASK)
304     return; /* currently waiting for bandwidth */
305   mq = n->messages_head;
306   while (NULL != (mq = n->messages_head))
307     {
308       timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
309       if (timeout.rel_value > 0)
310         break;
311       transmit_send_continuation (mq, &n->id, GNUNET_SYSERR); /* timeout */
312     }
313   if (NULL == mq)
314     return; /* no more messages */
315
316   papi = GST_plugins_find (n->plugin_name);
317   if (papi == NULL)
318     {
319       GNUNET_break (0);
320       return;
321     }
322   GNUNET_CONTAINER_DLL_remove (n->messages_head,
323                                n->messages_tail,
324                                mq);
325   n->is_active = mq;
326   mq->n = n;
327   ret = papi->send (papi->cls,
328                     &n->id,
329                     mq->message_buf,
330                     mq->message_buf_size,
331                     0 /* priority -- remove from plugin API? */,
332                     timeout,
333                     n->session,
334                     n->addr,
335                     n->addrlen,
336                     GNUNET_YES,
337                     &transmit_send_continuation, mq);
338   if (ret == -1)
339     {
340       /* failure, but 'send' would not call continuation in this case,
341          so we need to do it here! */
342       transmit_send_continuation (mq,
343                                   &n->id,
344                                   GNUNET_SYSERR);
345       n->transmission_task = GNUNET_SCHEDULER_add_now (&transmission_task,
346                                                        n);
347     }
348 }
349
350
351 /**
352  * Task invoked to start a transmission to another peer.
353  *
354  * @param cls the 'struct NeighbourMapEntry'
355  * @param tc scheduler context
356  */
357 static void
358 transmission_task (void *cls,
359                    const struct GNUNET_SCHEDULER_TaskContext *tc)
360 {
361   struct NeighbourMapEntry *n = cls;
362
363   n->transmission_task = GNUNET_SCHEDULER_NO_TASK;
364   try_transmission_to_peer (n);
365 }
366
367
368 /**
369  * Initialize the neighbours subsystem.
370  *
371  * @param cls closure for callbacks
372  * @param connect_cb function to call if we connect to a peer
373  * @param disconnect_cb function to call if we disconnect from a peer
374  */
375 void 
376 GST_neighbours_start (void *cls,
377                       GNUNET_TRANSPORT_NotifyConnect connect_cb,
378                       GNUNET_TRANSPORT_NotifyDisconnect disconnect_cb)
379 {
380   callback_cls = cls;
381   connect_notify_cb = connect_cb;
382   disconnect_notify_cb = disconnect_cb;
383   neighbours = GNUNET_CONTAINER_multihashmap_create (NEIGHBOUR_TABLE_SIZE);
384 }
385
386
387 /**
388  * Disconnect from the given neighbour, clean up the record.
389  *
390  * @param n neighbour to disconnect from
391  */
392 static void
393 disconnect_neighbour (struct NeighbourMapEntry *n)
394 {
395   struct MessageQueue *mq;
396
397   if (GNUNET_YES == n->in_disconnect)
398     return;
399   n->in_disconnect = GNUNET_YES;
400   while (NULL != (mq = n->messages_head))
401     {
402       GNUNET_CONTAINER_DLL_remove (n->messages_head,
403                                    n->messages_tail,
404                                    mq);
405       mq->cont (mq->cont_cls, GNUNET_SYSERR);
406       GNUNET_free (mq);
407     }
408   if (NULL != n->is_active)
409     {
410       n->is_active->n = NULL;
411       n->is_active = NULL;
412     }
413   if (GNUNET_YES == n->is_connected)
414     {
415       n->is_connected = GNUNET_NO;
416       disconnect_notify_cb (callback_cls,
417                             &n->id);
418     }
419   GNUNET_assert (GNUNET_YES ==
420                  GNUNET_CONTAINER_multihashmap_remove (neighbours,
421                                                        &n->id.hashPubKey,
422                                                        n));
423   if (GNUNET_SCHEDULER_NO_TASK != n->timeout_task)
424     {
425       GNUNET_SCHEDULER_cancel (n->timeout_task);
426       n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
427     }
428   if (GNUNET_SCHEDULER_NO_TASK != n->transmission_task)
429     {
430       GNUNET_SCHEDULER_cancel (n->timeout_task);
431       n->transmission_task = GNUNET_SCHEDULER_NO_TASK;
432     }
433   if (NULL != n->asc)
434     {
435       GNUNET_ATS_suggest_address_cancel (n->asc);
436       n->asc = NULL;
437     }
438   GNUNET_array_grow (n->ats,
439                      n->ats_count,
440                      0);
441   if (NULL != n->plugin_name)
442     {
443       GNUNET_free (n->plugin_name);
444       n->plugin_name = NULL;
445     }
446   if (NULL != n->addr)
447     {
448       GNUNET_free (n->addr);
449       n->addr = NULL;
450       n->addrlen = 0;
451     }
452   n->session = NULL;
453   GNUNET_free (n);
454 }
455
456
457 /**
458  * Peer has been idle for too long. Disconnect.
459  *
460  * @param cls the 'struct NeighbourMapEntry' of the neighbour that went idle
461  * @param tc scheduler context
462  */
463 static void
464 neighbour_timeout_task (void *cls,
465                         const struct GNUNET_SCHEDULER_TaskContext *tc)
466 {
467   struct NeighbourMapEntry *n = cls;
468
469   n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
470   disconnect_neighbour (n);
471 }
472
473
474 /**
475  * Disconnect from the given neighbour.
476  *
477  * @param cls unused
478  * @param key hash of neighbour's public key (not used)
479  * @param value the 'struct NeighbourMapEntry' of the neighbour
480  */
481 static int
482 disconnect_all_neighbours (void *cls,
483                            const GNUNET_HashCode *key,
484                            void *value)
485 {
486   struct NeighbourMapEntry *n = value;
487
488 #if DEBUG_TRANSPORT
489   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
490               "Disconnecting peer `%4s', %s\n",
491               GNUNET_i2s(&n->id),
492               "SHUTDOWN_TASK");
493 #endif
494   disconnect_neighbour (n);
495   return GNUNET_OK;
496 }
497
498
499 /**
500  * Cleanup the neighbours subsystem.
501  */
502 void
503 GST_neighbours_stop ()
504 {
505   GNUNET_CONTAINER_multihashmap_iterate (neighbours,
506                                          &disconnect_all_neighbours,
507                                          NULL);
508   GNUNET_CONTAINER_multihashmap_destroy (neighbours);
509   neighbours = NULL;
510   callback_cls = NULL;
511   connect_notify_cb = NULL;
512   disconnect_notify_cb = NULL;
513 }
514
515
516 /**
517  * For an existing neighbour record, set the active connection to
518  * the given address.
519  *
520  * @param plugin_name name of transport that delivered the PONG
521  * @param address address of the other peer, NULL if other peer
522  *                       connected to us
523  * @param address_len number of bytes in address
524  * @param ats performance data
525  * @param ats_count number of entries in ats (excluding 0-termination)
526  */
527 void
528 GST_neighbours_switch_to_address (const struct GNUNET_PeerIdentity *peer,
529                                   const char *plugin_name,
530                                   const void *address,
531                                   size_t address_len,
532                                   struct Session *session,
533                                   const struct GNUNET_TRANSPORT_ATS_Information *ats,
534                                   uint32_t ats_count)
535 {
536   struct NeighbourMapEntry *n;
537   struct GNUNET_MessageHeader connect_msg;
538
539   n = lookup_neighbour (peer);
540   if (NULL == n)
541     {
542       GNUNET_break (0);
543       return;
544     }
545   GNUNET_free_non_null (n->addr);
546   n->addr = GNUNET_malloc (address_len);
547   memcpy (n->addr, address, address_len);
548   n->addrlen = address_len;
549   n->session = session;
550   GNUNET_array_grow (n->ats,
551                      n->ats_count,
552                      ats_count);
553   memcpy (n->ats,
554           ats,
555           ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information));
556   GNUNET_free_non_null (n->plugin_name);
557   n->plugin_name = GNUNET_strdup (plugin_name);
558   GNUNET_SCHEDULER_cancel (n->timeout_task);
559   n->timeout_task =
560     GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
561                                   &neighbour_timeout_task, n);
562   connect_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
563   connect_msg.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
564   GST_neighbours_send (peer,
565                        &connect_msg,
566                        sizeof (connect_msg),
567                        GNUNET_TIME_UNIT_FOREVER_REL,
568                        NULL, NULL);
569 }
570
571
572 /**
573  * Try to connect to the target peer using the given address
574  *
575  * @param cls the 'struct NeighbourMapEntry' of the target
576  * @param target identity of the target peer
577  * @param plugin_name name of the plugin
578  * @param plugin_address binary address
579  * @param plugin_address_len length of address
580  * @param bandwidth available bandwidth
581  * @param ats performance data for the address (as far as known)
582  * @param ats_count number of performance records in 'ats'
583  */
584 static void
585 try_connect_using_address (void *cls,
586                            const struct GNUNET_PeerIdentity *target,
587                            const char *plugin_name,
588                            const void *plugin_address,
589                            size_t plugin_address_len,
590                            struct GNUNET_BANDWIDTH_Value32NBO bandwidth,
591                            const struct GNUNET_TRANSPORT_ATS_Information *ats,
592                            uint32_t ats_count)
593 {
594   struct NeighbourMapEntry *n = cls;
595
596   n->asc = NULL;
597   GST_neighbours_switch_to_address (target,
598                                     plugin_name,
599                                     plugin_address,
600                                     plugin_address_len,
601                                     NULL,
602                                     ats, ats_count);
603   if (GNUNET_YES == n->is_connected)
604     return;
605   n->is_connected = GNUNET_YES;  
606   connect_notify_cb (callback_cls,
607                      target,
608                      n->ats,
609                      n->ats_count);
610 }
611
612
613 /**
614  * Try to create a connection to the given target (eventually).
615  *
616  * @param target peer to try to connect to
617  */
618 void
619 GST_neighbours_try_connect (const struct GNUNET_PeerIdentity *target)
620 {
621   struct NeighbourMapEntry *n;
622
623   GNUNET_assert (0 != memcmp (target,
624                               &GST_my_identity,
625                               sizeof (struct GNUNET_PeerIdentity)));
626   n = lookup_neighbour (target);
627   if ( (NULL != n) &&
628        (GNUNET_YES == n->is_connected) )
629     return; /* already connected */
630   if (n == NULL)
631     {
632       n = GNUNET_malloc (sizeof (struct NeighbourMapEntry));
633       n->id = *target;
634       GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
635                                      GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
636                                      MAX_BANDWIDTH_CARRY_S);
637       n->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
638                                                       &neighbour_timeout_task, n);
639       GNUNET_assert (GNUNET_OK ==
640                      GNUNET_CONTAINER_multihashmap_put (neighbours,
641                                                         &n->id.hashPubKey,
642                                                         n,
643                                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
644     }
645   if (n->asc != NULL)
646     return; /* already trying */
647   n->asc = GNUNET_ATS_suggest_address (GST_ats,
648                                        target,
649                                        &try_connect_using_address,
650                                        n); 
651 }
652
653
654 /**
655  * Test if we're connected to the given peer.
656  * 
657  * @param target peer to test
658  * @return GNUNET_YES if we are connected, GNUNET_NO if not
659  */
660 int
661 GST_neighbours_test_connected (const struct GNUNET_PeerIdentity *target)
662 {
663   struct NeighbourMapEntry *n;
664
665   n = lookup_neighbour (target);
666   if ( (NULL == n) ||
667        (n->is_connected == GNUNET_YES) )
668        return GNUNET_NO; /* not connected */
669   return GNUNET_YES;
670 }
671
672
673 /**
674  * Transmit a message to the given target using the active connection.
675  *
676  * @param target destination
677  * @param msg message to send
678  * @param msg_size number of bytes in msg
679  * @param timeout when to fail with timeout
680  * @param cont function to call when done
681  * @param cont_cls closure for 'cont'
682  */
683 void
684 GST_neighbours_send (const struct GNUNET_PeerIdentity *target,
685                      const void *msg,
686                      size_t msg_size,
687                      struct GNUNET_TIME_Relative timeout,
688                      GST_NeighbourSendContinuation cont,
689                      void *cont_cls)
690 {
691   struct NeighbourMapEntry *n;
692   struct MessageQueue *mq;
693
694   n = lookup_neighbour (target);
695   if ( (n == NULL) ||
696        (GNUNET_YES != n->is_connected) )
697     {
698       GNUNET_STATISTICS_update (GST_stats,
699                                 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
700                                 1,
701                                 GNUNET_NO);
702       if (NULL != cont)
703         cont (cont_cls,
704               GNUNET_SYSERR);
705       return;
706     }
707   GNUNET_assert (msg_size >= sizeof (struct GNUNET_MessageHeader));
708   GNUNET_STATISTICS_update (GST_stats,
709                             gettext_noop ("# bytes in message queue for other peers"),
710                             msg_size,
711                             GNUNET_NO);
712   mq = GNUNET_malloc (sizeof (struct MessageQueue) + msg_size);
713   mq->cont = cont;
714   mq->cont_cls = cont_cls;
715   /* FIXME: this memcpy can be up to 7% of our total runtime! */
716   memcpy (&mq[1], msg, msg_size);
717   mq->message_buf = (const char*) &mq[1];
718   mq->message_buf_size = msg_size;
719   mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
720   GNUNET_CONTAINER_DLL_insert_tail (n->messages_head,
721                                     n->messages_tail,
722                                     mq);
723   if ( (GNUNET_SCHEDULER_NO_TASK == n->transmission_task) &&
724        (NULL == n->is_active) )
725     n->transmission_task = GNUNET_SCHEDULER_add_now (&transmission_task,
726                                                      n);
727 }
728
729
730 /**
731  * We have received a message from the given sender.  How long should
732  * we delay before receiving more?  (Also used to keep the peer marked
733  * as live).
734  *
735  * @param sender sender of the message
736  * @param size size of the message
737  * @return how long to wait before reading more from this sender
738  */
739 struct GNUNET_TIME_Relative
740 GST_neighbours_calculate_receive_delay (const struct GNUNET_PeerIdentity *sender,
741                                         ssize_t size)
742 {
743   struct NeighbourMapEntry *n;
744   struct GNUNET_TIME_Relative ret;
745
746   n = lookup_neighbour (sender);
747   if (n == NULL)
748     return GNUNET_TIME_UNIT_ZERO;
749   if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
750                                                       size))
751     {
752       n->quota_violation_count++;
753 #if DEBUG_TRANSPORT
754       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
755                   "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
756                   n->in_tracker.available_bytes_per_s__,
757                   n->quota_violation_count);
758 #endif
759       /* Discount 32k per violation */
760       GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
761                                         - 32 * 1024);
762     }
763   else
764     {
765       if (n->quota_violation_count > 0)
766         {
767           /* try to add 32k back */
768           GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
769                                             32 * 1024);
770           n->quota_violation_count--;
771         }
772     }
773   GNUNET_SCHEDULER_cancel (n->timeout_task);
774   n->timeout_task =
775     GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
776                                   &neighbour_timeout_task, n);
777   if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
778     {
779       GNUNET_STATISTICS_update (GST_stats,
780                                 gettext_noop ("# bandwidth quota violations by other peers"),
781                                 1,
782                                 GNUNET_NO);
783       return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
784     }
785   ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
786   if (ret.rel_value > 0)
787     {
788 #if DEBUG_TRANSPORT 
789       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
790                   "Throttling read (%llu bytes excess at %u b/s), waiting %llu ms before reading more.\n",
791                   (unsigned long long) n->in_tracker.consumption_since_last_update__,
792                   (unsigned int) n->in_tracker.available_bytes_per_s__,
793                   (unsigned long long) ret.rel_value);
794 #endif
795       GNUNET_STATISTICS_update (GST_stats,
796                                 gettext_noop ("# ms throttling suggested"),
797                                 (int64_t) ret.rel_value,
798                                 GNUNET_NO);
799     }
800   return ret;
801 }
802
803
804 /**
805  * Change the incoming quota for the given peer.
806  *
807  * @param neighbour identity of peer to change qutoa for
808  * @param quota new quota 
809  */
810 void
811 GST_neighbours_set_incoming_quota (const struct GNUNET_PeerIdentity *neighbour,
812                                    struct GNUNET_BANDWIDTH_Value32NBO quota)
813 {
814   struct NeighbourMapEntry *n;
815
816   n = lookup_neighbour (neighbour);
817   if (n == NULL)
818     {
819       GNUNET_STATISTICS_update (GST_stats,
820                                 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
821                                 1,
822                                 GNUNET_NO);
823       return;
824     }
825   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
826                                          quota);
827   if (0 != ntohl (quota.value__))
828     return;
829 #if DEBUG_TRANSPORT
830   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
831               "Disconnecting peer `%4s' due to `%s'\n",
832               GNUNET_i2s(&n->id),
833               "SET_QUOTA");
834 #endif
835   GNUNET_STATISTICS_update (GST_stats,
836                             gettext_noop ("# disconnects due to quota of 0"),
837                             1,
838                             GNUNET_NO);
839   disconnect_neighbour (n);
840 }
841
842
843 /**
844  * Closure for the neighbours_iterate function.
845  */
846 struct IteratorContext
847 {
848   /**
849    * Function to call on each connected neighbour.
850    */
851   GST_NeighbourIterator cb;
852
853   /**
854    * Closure for 'cb'.
855    */
856   void *cb_cls;
857 };
858
859
860 /**
861  * Call the callback from the closure for each connected neighbour.
862  *
863  * @param cls the 'struct IteratorContext'
864  * @param key the hash of the public key of the neighbour
865  * @param value the 'struct NeighbourMapEntry'
866  * @return GNUNET_OK (continue to iterate)
867  */
868 static int
869 neighbours_iterate (void *cls,
870                     const GNUNET_HashCode *key,
871                     void *value)
872 {
873   struct IteratorContext *ic = cls;
874   struct NeighbourMapEntry *n = value;
875
876   if (GNUNET_YES != n->is_connected)
877     return GNUNET_OK; 
878   GNUNET_assert (n->ats_count > 0);
879   ic->cb (ic->cb_cls,
880           &n->id,
881           n->ats,
882           n->ats_count - 1);
883   return GNUNET_OK;
884 }
885
886
887 /**
888  * Iterate over all connected neighbours.
889  *
890  * @param cb function to call 
891  * @param cb_cls closure for cb
892  */
893 void
894 GST_neighbours_iterate (GST_NeighbourIterator cb,
895                         void *cb_cls)
896 {
897   struct IteratorContext ic;
898
899   ic.cb = cb;
900   ic.cb_cls = cb_cls;
901   GNUNET_CONTAINER_multihashmap_iterate (neighbours,
902                                          &neighbours_iterate,
903                                          &ic);
904 }
905
906
907 /**
908  * If we have an active connection to the given target, it must be shutdown.
909  *
910  * @param target peer to disconnect from
911  */
912 void
913 GST_neighbours_force_disconnect (const struct GNUNET_PeerIdentity *target)
914 {
915   struct NeighbourMapEntry *n;
916   struct GNUNET_TRANSPORT_PluginFunctions *papi;
917   struct GNUNET_MessageHeader disconnect_msg;
918
919   n = lookup_neighbour (target);
920   disconnect_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
921   disconnect_msg.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
922   papi = GST_plugins_find (n->plugin_name);
923   if (papi != NULL)
924     papi->send (papi->cls,
925                 target,
926                 (const void*) &disconnect_msg,
927                 sizeof (struct GNUNET_MessageHeader),
928                 UINT32_MAX /* priority */,
929                 GNUNET_TIME_UNIT_FOREVER_REL,
930                 n->session,
931                 n->addr,
932                 n->addrlen,
933                 GNUNET_YES,
934                 NULL, NULL);
935   disconnect_neighbour (n);
936 }
937
938
939 /* end of file gnunet-service-transport_neighbours.c */