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