stuff
[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  * A session was terminated. Take note.
518  *
519  * @param peer identity of the peer where the session died
520  * @param session session that is gone
521  */
522 void
523 GST_neighbours_session_terminated (const struct GNUNET_PeerIdentity *peer,
524                                    struct Session *session)
525 {
526   struct NeighbourMapEntry *n;
527
528   n = lookup_neighbour (peer);
529   if (NULL == n)
530     return;
531   if (session == n->session)
532     n->session = NULL;
533 }
534
535
536 /**
537  * For an existing neighbour record, set the active connection to
538  * the given address.
539  *
540  * @param peer identity of the peer to switch the address for
541  * @param plugin_name name of transport that delivered the PONG
542  * @param address address of the other peer, NULL if other peer
543  *                       connected to us
544  * @param address_len number of bytes in address
545  * @param session session to use (or NULL)
546  * @param ats performance data
547  * @param ats_count number of entries in ats (excluding 0-termination)
548  */
549 void
550 GST_neighbours_switch_to_address (const struct GNUNET_PeerIdentity *peer,
551                                   const char *plugin_name,
552                                   const void *address,
553                                   size_t address_len,
554                                   struct Session *session,
555                                   const struct GNUNET_TRANSPORT_ATS_Information *ats,
556                                   uint32_t ats_count)
557 {
558   struct NeighbourMapEntry *n;
559   struct GNUNET_MessageHeader connect_msg;
560
561   n = lookup_neighbour (peer);
562   if (NULL == n)
563     {
564       GNUNET_break (0);
565       return;
566     }
567   GNUNET_free_non_null (n->addr);
568   n->addr = GNUNET_malloc (address_len);
569   memcpy (n->addr, address, address_len);
570   n->addrlen = address_len;
571   n->session = session;
572   GNUNET_array_grow (n->ats,
573                      n->ats_count,
574                      ats_count);
575   memcpy (n->ats,
576           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.size = htons (sizeof (struct GNUNET_MessageHeader));
585   connect_msg.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
586   GST_neighbours_send (peer,
587                        &connect_msg,
588                        sizeof (connect_msg),
589                        GNUNET_TIME_UNIT_FOREVER_REL,
590                        NULL, NULL);
591 }
592
593
594 /**
595  * Try to connect to the target peer using the given address
596  *
597  * @param cls the 'struct NeighbourMapEntry' of the target
598  * @param target identity of the target peer
599  * @param plugin_name name of the plugin
600  * @param plugin_address binary address
601  * @param plugin_address_len length of address
602  * @param bandwidth available bandwidth
603  * @param ats performance data for the address (as far as known)
604  * @param ats_count number of performance records in 'ats'
605  */
606 static void
607 try_connect_using_address (void *cls,
608                            const struct GNUNET_PeerIdentity *target,
609                            const char *plugin_name,
610                            const void *plugin_address,
611                            size_t plugin_address_len,
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
618   n->asc = NULL;
619   GST_neighbours_switch_to_address (target,
620                                     plugin_name,
621                                     plugin_address,
622                                     plugin_address_len,
623                                     NULL,
624                                     ats, ats_count);
625   if (GNUNET_YES == n->is_connected)
626     return;
627   n->is_connected = GNUNET_YES;  
628   connect_notify_cb (callback_cls,
629                      target,
630                      n->ats,
631                      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 (0 != memcmp (target,
646                               &GST_my_identity,
647                               sizeof (struct GNUNET_PeerIdentity)));
648   n = lookup_neighbour (target);
649   if ( (NULL != n) &&
650        (GNUNET_YES == n->is_connected) )
651     return; /* already connected */
652   if (n == NULL)
653     {
654       n = GNUNET_malloc (sizeof (struct NeighbourMapEntry));
655       n->id = *target;
656       GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
657                                      GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
658                                      MAX_BANDWIDTH_CARRY_S);
659       n->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
660                                                       &neighbour_timeout_task, n);
661       GNUNET_assert (GNUNET_OK ==
662                      GNUNET_CONTAINER_multihashmap_put (neighbours,
663                                                         &n->id.hashPubKey,
664                                                         n,
665                                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
666     }
667   if (n->asc != NULL)
668     return; /* already trying */
669   n->asc = GNUNET_ATS_suggest_address (GST_ats,
670                                        target,
671                                        &try_connect_using_address,
672                                        n); 
673 }
674
675
676 /**
677  * Test if we're connected to the given peer.
678  * 
679  * @param target peer to test
680  * @return GNUNET_YES if we are connected, GNUNET_NO if not
681  */
682 int
683 GST_neighbours_test_connected (const struct GNUNET_PeerIdentity *target)
684 {
685   struct NeighbourMapEntry *n;
686
687   n = lookup_neighbour (target);
688   if ( (NULL == n) ||
689        (n->is_connected == GNUNET_YES) )
690        return GNUNET_NO; /* not connected */
691   return GNUNET_YES;
692 }
693
694
695 /**
696  * Transmit a message to the given target using the active connection.
697  *
698  * @param target destination
699  * @param msg message to send
700  * @param msg_size number of bytes in msg
701  * @param timeout when to fail with timeout
702  * @param cont function to call when done
703  * @param cont_cls closure for 'cont'
704  */
705 void
706 GST_neighbours_send (const struct GNUNET_PeerIdentity *target,
707                      const void *msg,
708                      size_t msg_size,
709                      struct GNUNET_TIME_Relative timeout,
710                      GST_NeighbourSendContinuation cont,
711                      void *cont_cls)
712 {
713   struct NeighbourMapEntry *n;
714   struct MessageQueue *mq;
715
716   n = lookup_neighbour (target);
717   if ( (n == NULL) ||
718        (GNUNET_YES != n->is_connected) )
719     {
720       GNUNET_STATISTICS_update (GST_stats,
721                                 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
722                                 1,
723                                 GNUNET_NO);
724       if (NULL != cont)
725         cont (cont_cls,
726               GNUNET_SYSERR);
727       return;
728     }
729   GNUNET_assert (msg_size >= sizeof (struct GNUNET_MessageHeader));
730   GNUNET_STATISTICS_update (GST_stats,
731                             gettext_noop ("# bytes in message queue for other peers"),
732                             msg_size,
733                             GNUNET_NO);
734   mq = GNUNET_malloc (sizeof (struct MessageQueue) + msg_size);
735   mq->cont = cont;
736   mq->cont_cls = cont_cls;
737   /* FIXME: this memcpy can be up to 7% of our total runtime! */
738   memcpy (&mq[1], msg, msg_size);
739   mq->message_buf = (const char*) &mq[1];
740   mq->message_buf_size = msg_size;
741   mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
742   GNUNET_CONTAINER_DLL_insert_tail (n->messages_head,
743                                     n->messages_tail,
744                                     mq);
745   if ( (GNUNET_SCHEDULER_NO_TASK == n->transmission_task) &&
746        (NULL == n->is_active) )
747     n->transmission_task = GNUNET_SCHEDULER_add_now (&transmission_task,
748                                                      n);
749 }
750
751
752 /**
753  * We have received a message from the given sender.  How long should
754  * we delay before receiving more?  (Also used to keep the peer marked
755  * as live).
756  *
757  * @param sender sender of the message
758  * @param size size of the message
759  * @return how long to wait before reading more from this sender
760  */
761 struct GNUNET_TIME_Relative
762 GST_neighbours_calculate_receive_delay (const struct GNUNET_PeerIdentity *sender,
763                                         ssize_t size)
764 {
765   struct NeighbourMapEntry *n;
766   struct GNUNET_TIME_Relative ret;
767
768   n = lookup_neighbour (sender);
769   if (n == NULL)
770     return GNUNET_TIME_UNIT_ZERO;
771   if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
772                                                       size))
773     {
774       n->quota_violation_count++;
775 #if DEBUG_TRANSPORT
776       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
777                   "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
778                   n->in_tracker.available_bytes_per_s__,
779                   n->quota_violation_count);
780 #endif
781       /* Discount 32k per violation */
782       GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
783                                         - 32 * 1024);
784     }
785   else
786     {
787       if (n->quota_violation_count > 0)
788         {
789           /* try to add 32k back */
790           GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker,
791                                             32 * 1024);
792           n->quota_violation_count--;
793         }
794     }
795   GNUNET_SCHEDULER_cancel (n->timeout_task);
796   n->timeout_task =
797     GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
798                                   &neighbour_timeout_task, n);
799   if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
800     {
801       GNUNET_STATISTICS_update (GST_stats,
802                                 gettext_noop ("# bandwidth quota violations by other peers"),
803                                 1,
804                                 GNUNET_NO);
805       return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
806     }
807   ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
808   if (ret.rel_value > 0)
809     {
810 #if DEBUG_TRANSPORT 
811       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
812                   "Throttling read (%llu bytes excess at %u b/s), waiting %llu ms before reading more.\n",
813                   (unsigned long long) n->in_tracker.consumption_since_last_update__,
814                   (unsigned int) n->in_tracker.available_bytes_per_s__,
815                   (unsigned long long) ret.rel_value);
816 #endif
817       GNUNET_STATISTICS_update (GST_stats,
818                                 gettext_noop ("# ms throttling suggested"),
819                                 (int64_t) ret.rel_value,
820                                 GNUNET_NO);
821     }
822   return ret;
823 }
824
825
826 /**
827  * Change the incoming quota for the given peer.
828  *
829  * @param neighbour identity of peer to change qutoa for
830  * @param quota new quota 
831  */
832 void
833 GST_neighbours_set_incoming_quota (const struct GNUNET_PeerIdentity *neighbour,
834                                    struct GNUNET_BANDWIDTH_Value32NBO quota)
835 {
836   struct NeighbourMapEntry *n;
837
838   n = lookup_neighbour (neighbour);
839   if (n == NULL)
840     {
841       GNUNET_STATISTICS_update (GST_stats,
842                                 gettext_noop ("# SET QUOTA messages ignored (no such peer)"),
843                                 1,
844                                 GNUNET_NO);
845       return;
846     }
847   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker,
848                                          quota);
849   if (0 != ntohl (quota.value__))
850     return;
851 #if DEBUG_TRANSPORT
852   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
853               "Disconnecting peer `%4s' due to `%s'\n",
854               GNUNET_i2s(&n->id),
855               "SET_QUOTA");
856 #endif
857   GNUNET_STATISTICS_update (GST_stats,
858                             gettext_noop ("# disconnects due to quota of 0"),
859                             1,
860                             GNUNET_NO);
861   disconnect_neighbour (n);
862 }
863
864
865 /**
866  * Closure for the neighbours_iterate function.
867  */
868 struct IteratorContext
869 {
870   /**
871    * Function to call on each connected neighbour.
872    */
873   GST_NeighbourIterator cb;
874
875   /**
876    * Closure for 'cb'.
877    */
878   void *cb_cls;
879 };
880
881
882 /**
883  * Call the callback from the closure for each connected neighbour.
884  *
885  * @param cls the 'struct IteratorContext'
886  * @param key the hash of the public key of the neighbour
887  * @param value the 'struct NeighbourMapEntry'
888  * @return GNUNET_OK (continue to iterate)
889  */
890 static int
891 neighbours_iterate (void *cls,
892                     const GNUNET_HashCode *key,
893                     void *value)
894 {
895   struct IteratorContext *ic = cls;
896   struct NeighbourMapEntry *n = value;
897
898   if (GNUNET_YES != n->is_connected)
899     return GNUNET_OK; 
900   GNUNET_assert (n->ats_count > 0);
901   ic->cb (ic->cb_cls,
902           &n->id,
903           n->ats,
904           n->ats_count - 1);
905   return GNUNET_OK;
906 }
907
908
909 /**
910  * Iterate over all connected neighbours.
911  *
912  * @param cb function to call 
913  * @param cb_cls closure for cb
914  */
915 void
916 GST_neighbours_iterate (GST_NeighbourIterator cb,
917                         void *cb_cls)
918 {
919   struct IteratorContext ic;
920
921   ic.cb = cb;
922   ic.cb_cls = cb_cls;
923   GNUNET_CONTAINER_multihashmap_iterate (neighbours,
924                                          &neighbours_iterate,
925                                          &ic);
926 }
927
928
929 /**
930  * If we have an active connection to the given target, it must be shutdown.
931  *
932  * @param target peer to disconnect from
933  */
934 void
935 GST_neighbours_force_disconnect (const struct GNUNET_PeerIdentity *target)
936 {
937   struct NeighbourMapEntry *n;
938   struct GNUNET_TRANSPORT_PluginFunctions *papi;
939   struct GNUNET_MessageHeader disconnect_msg;
940
941   n = lookup_neighbour (target);
942   disconnect_msg.size = htons (sizeof (struct GNUNET_MessageHeader));
943   disconnect_msg.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT);
944   papi = GST_plugins_find (n->plugin_name);
945   if (papi != NULL)
946     papi->send (papi->cls,
947                 target,
948                 (const void*) &disconnect_msg,
949                 sizeof (struct GNUNET_MessageHeader),
950                 UINT32_MAX /* priority */,
951                 GNUNET_TIME_UNIT_FOREVER_REL,
952                 n->session,
953                 n->addr,
954                 n->addrlen,
955                 GNUNET_YES,
956                 NULL, NULL);
957   disconnect_neighbour (n);
958 }
959
960
961 /* end of file gnunet-service-transport_neighbours.c */