modifiying transport service
[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), GNUNET_i2s (target));
739 #endif
740
741
742   GST_neighbours_set_incoming_quota (&n->id, bandwidth_in);
743   /* ATS told us outbound quota for this peer, tell all clients */
744 #if DEBUG_TRANSPORT
745   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending outbound quota of %u Bps for peer `%s' to all clients\n",
746               ntohl (bandwidth_out), GNUNET_i2s (target));
747 #endif
748
749   struct QuotaSetMessage msg;
750   msg.header.size = htons (sizeof (struct QuotaSetMessage));
751   msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA);
752   msg.quota = bandwidth_out;
753   msg.peer = (*target);
754   GST_clients_broadcast ((struct GNUNET_MessageHeader *) &msg, GNUNET_NO);
755
756   neighbours_connected++;
757   GNUNET_STATISTICS_update (GST_stats, gettext_noop ("# peers connected"), 1,
758                             GNUNET_NO);
759   connect_notify_cb (callback_cls, target, n->ats, n->ats_count);
760 }
761
762
763 /**
764  * Try to create a connection to the given target (eventually).
765  *
766  * @param target peer to try to connect to
767  */
768 void
769 GST_neighbours_try_connect (const struct GNUNET_PeerIdentity *target)
770 {
771   struct NeighbourMapEntry *n;
772
773   GNUNET_assert (neighbours != NULL);
774
775 #if DEBUG_TRANSPORT
776   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Trying to connect to peer `%s'\n",
777               GNUNET_i2s (target));
778 #endif
779
780   GNUNET_assert (0 !=
781                  memcmp (target, &GST_my_identity,
782                          sizeof (struct GNUNET_PeerIdentity)));
783   n = lookup_neighbour (target);
784   if ((NULL != n) && (GNUNET_YES == n->is_connected))
785     return;                     /* already connected */
786   if (n == NULL)
787   {
788 #if DEBUG_TRANSPORT
789     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
790                 "Unknown peer `%s', creating new neighbour\n",
791                 GNUNET_i2s (target));
792 #endif
793     n = GNUNET_malloc (sizeof (struct NeighbourMapEntry));
794     n->id = *target;
795     GNUNET_array_grow (n->ats, n->ats_count, 1);
796     n->ats[0].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);;
797     n->ats[0].value = htonl (0);
798     GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
799                                    GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
800                                    MAX_BANDWIDTH_CARRY_S);
801     n->timeout_task =
802         GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
803                                       &neighbour_timeout_task, n);
804     GNUNET_assert (GNUNET_OK ==
805                    GNUNET_CONTAINER_multihashmap_put (neighbours,
806                                                       &n->id.hashPubKey, n,
807                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
808   }
809   if (n->asc != NULL)
810     return;                     /* already trying */
811 #if DEBUG_TRANSPORT
812   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
813               "Asking ATS for suggested address to connect to peer `%s'\n",
814               GNUNET_i2s (target));
815 #endif
816   n->asc =
817       GNUNET_ATS_suggest_address (GST_ats, target, &try_connect_using_address,
818                                   n);
819 }
820
821
822 /**
823  * Test if we're connected to the given peer.
824  *
825  * @param target peer to test
826  * @return GNUNET_YES if we are connected, GNUNET_NO if not
827  */
828 int
829 GST_neighbours_test_connected (const struct GNUNET_PeerIdentity *target)
830 {
831   struct NeighbourMapEntry *n;
832
833   GNUNET_assert (neighbours != NULL);
834
835   n = lookup_neighbour (target);
836   if ((NULL == n) || (n->is_connected != GNUNET_YES))
837     return GNUNET_NO;           /* not connected */
838   return GNUNET_YES;
839 }
840
841
842 /**
843  * A session was terminated. Take note.
844  *
845  * @param peer identity of the peer where the session died
846  * @param session session that is gone
847  */
848 void
849 GST_neighbours_session_terminated (const struct GNUNET_PeerIdentity *peer,
850                                    struct Session *session)
851 {
852   struct NeighbourMapEntry *n;
853
854   GNUNET_assert (neighbours != NULL);
855
856 #if DEBUG_TRANSPORT
857   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
858               "Session %X to peer `%s' ended \n",
859               session, GNUNET_i2s (peer));
860 #endif
861
862   n = lookup_neighbour (peer);
863   if (NULL == n)
864     return;
865   if (session != n->session)
866     return;                     /* doesn't affect us */
867
868   n->session = NULL;
869   GNUNET_free (n->addr);
870   n->addr = NULL;
871   n->addrlen = 0;
872
873
874   if (GNUNET_YES != n->is_connected)
875     return;                     /* not connected anymore anyway, shouldn't matter */
876
877   //n->is_connected = GNUNET_NO;
878
879   /* fast disconnect unless ATS suggests a new address */
880   GNUNET_SCHEDULER_cancel (n->timeout_task);
881   n->timeout_task =
882       GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
883                                     &neighbour_timeout_task, n);
884   /* try QUICKLY to re-establish a connection, reduce timeout! */
885   if (NULL != n->ats)
886   {
887     /* how can this be!? */
888     //GNUNET_break (0);
889     return;
890   }
891   n->asc =
892       GNUNET_ATS_suggest_address (GST_ats, peer, &try_connect_using_address, n);
893 }
894
895
896 /**
897  * Transmit a message to the given target using the active connection.
898  *
899  * @param target destination
900  * @param msg message to send
901  * @param msg_size number of bytes in msg
902  * @param timeout when to fail with timeout
903  * @param cont function to call when done
904  * @param cont_cls closure for 'cont'
905  */
906 void
907 GST_neighbours_send (const struct GNUNET_PeerIdentity *target, const void *msg,
908                      size_t msg_size, struct GNUNET_TIME_Relative timeout,
909                      GST_NeighbourSendContinuation cont, void *cont_cls)
910 {
911   struct NeighbourMapEntry *n;
912   struct MessageQueue *mq;
913
914   GNUNET_assert (neighbours != NULL);
915
916   n = lookup_neighbour (target);
917   if ((n == NULL) || (GNUNET_YES != n->is_connected))
918   {
919     GNUNET_STATISTICS_update (GST_stats,
920                               gettext_noop
921                               ("# messages not sent (no such peer or not connected)"),
922                               1, GNUNET_NO);
923 #if DEBUG_TRANSPORT
924     if (n == NULL)
925       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
926                   "Could not send message to peer `%s': unknown neighbor",
927                   GNUNET_i2s (target));
928     else if (GNUNET_YES != n->is_connected)
929       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
930                   "Could not send message to peer `%s': not connected\n",
931                   GNUNET_i2s (target));
932 #endif
933     if (NULL != cont)
934       cont (cont_cls, GNUNET_SYSERR);
935     return;
936   }
937
938   if ((n->session == NULL) && (n->addr == NULL) && (n->addrlen ==0))
939   {
940     GNUNET_STATISTICS_update (GST_stats,
941                               gettext_noop
942                               ("# messages not sent (no such peer or not connected)"),
943                               1, GNUNET_NO);
944 #if DEBUG_TRANSPORT
945       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
946                   "Could not send message to peer `%s': no address available\n",
947                   GNUNET_i2s (target));
948 #endif
949
950     if (NULL != cont)
951       cont (cont_cls, GNUNET_SYSERR);
952     return;
953   }
954
955
956   GNUNET_assert (msg_size >= sizeof (struct GNUNET_MessageHeader));
957   GNUNET_STATISTICS_update (GST_stats,
958                             gettext_noop
959                             ("# bytes in message queue for other peers"),
960                             msg_size, GNUNET_NO);
961   mq = GNUNET_malloc (sizeof (struct MessageQueue) + msg_size);
962   mq->cont = cont;
963   mq->cont_cls = cont_cls;
964   /* FIXME: this memcpy can be up to 7% of our total runtime! */
965   memcpy (&mq[1], msg, msg_size);
966   mq->message_buf = (const char *) &mq[1];
967   mq->message_buf_size = msg_size;
968   mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
969   GNUNET_CONTAINER_DLL_insert_tail (n->messages_head, n->messages_tail, mq);
970   if ((GNUNET_SCHEDULER_NO_TASK == n->transmission_task) &&
971       (NULL == n->is_active))
972     n->transmission_task = GNUNET_SCHEDULER_add_now (&transmission_task, n);
973 }
974
975
976 /**
977  * We have received a message from the given sender.  How long should
978  * we delay before receiving more?  (Also used to keep the peer marked
979  * as live).
980  *
981  * @param sender sender of the message
982  * @param size size of the message
983  * @param do_forward set to GNUNET_YES if the message should be forwarded to clients
984  *                   GNUNET_NO if the neighbour is not connected or violates the quota
985  * @return how long to wait before reading more from this sender
986  */
987 struct GNUNET_TIME_Relative
988 GST_neighbours_calculate_receive_delay (const struct GNUNET_PeerIdentity
989                                         *sender, ssize_t size, int *do_forward)
990 {
991   struct NeighbourMapEntry *n;
992   struct GNUNET_TIME_Relative ret;
993
994   GNUNET_assert (neighbours != NULL);
995
996   n = lookup_neighbour (sender);
997   if (n == NULL)
998   {
999     *do_forward = GNUNET_NO;
1000     return GNUNET_TIME_UNIT_ZERO;
1001   }
1002   if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, size))
1003   {
1004     n->quota_violation_count++;
1005 #if DEBUG_TRANSPORT
1006     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1007                 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
1008                 n->in_tracker.available_bytes_per_s__,
1009                 n->quota_violation_count);
1010 #endif
1011     /* Discount 32k per violation */
1012     GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, -32 * 1024);
1013   }
1014   else
1015   {
1016     if (n->quota_violation_count > 0)
1017     {
1018       /* try to add 32k back */
1019       GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, 32 * 1024);
1020       n->quota_violation_count--;
1021     }
1022   }
1023   if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
1024   {
1025     GNUNET_STATISTICS_update (GST_stats,
1026                               gettext_noop
1027                               ("# bandwidth quota violations by other peers"),
1028                               1, GNUNET_NO);
1029     *do_forward = GNUNET_NO;
1030     return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
1031   }
1032   *do_forward = GNUNET_YES;
1033   ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 0);
1034   if (ret.rel_value > 0)
1035   {
1036 #if DEBUG_TRANSPORT
1037     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1038                 "Throttling read (%llu bytes excess at %u b/s), waiting %llu ms before reading more.\n",
1039                 (unsigned long long) n->in_tracker.
1040                 consumption_since_last_update__,
1041                 (unsigned int) n->in_tracker.available_bytes_per_s__,
1042                 (unsigned long long) ret.rel_value);
1043 #endif
1044     GNUNET_STATISTICS_update (GST_stats,
1045                               gettext_noop ("# ms throttling suggested"),
1046                               (int64_t) ret.rel_value, GNUNET_NO);
1047   }
1048   return ret;
1049 }
1050
1051
1052 /**
1053  * Keep the connection to the given neighbour alive longer,
1054  * we received a KEEPALIVE (or equivalent).
1055  *
1056  * @param neighbour neighbour to keep alive
1057  */
1058 void
1059 GST_neighbours_keepalive (const struct GNUNET_PeerIdentity *neighbour)
1060 {
1061   struct NeighbourMapEntry *n;
1062
1063   GNUNET_assert (neighbours != NULL);
1064
1065   n = lookup_neighbour (neighbour);
1066   if (NULL == n)
1067   {
1068     GNUNET_STATISTICS_update (GST_stats,
1069                               gettext_noop
1070                               ("# KEEPALIVE messages discarded (not connected)"),
1071                               1, GNUNET_NO);
1072     return;
1073   }
1074   GNUNET_SCHEDULER_cancel (n->timeout_task);
1075   n->timeout_task =
1076       GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1077                                     &neighbour_timeout_task, n);
1078 }
1079
1080
1081 /**
1082  * Change the incoming quota for the given peer.
1083  *
1084  * @param neighbour identity of peer to change qutoa for
1085  * @param quota new quota
1086  */
1087 void
1088 GST_neighbours_set_incoming_quota (const struct GNUNET_PeerIdentity *neighbour,
1089                                    struct GNUNET_BANDWIDTH_Value32NBO quota)
1090 {
1091   struct NeighbourMapEntry *n;
1092
1093   GNUNET_assert (neighbours != NULL);
1094
1095   n = lookup_neighbour (neighbour);
1096   if (n == NULL)
1097   {
1098     GNUNET_STATISTICS_update (GST_stats,
1099                               gettext_noop
1100                               ("# SET QUOTA messages ignored (no such peer)"),
1101                               1, GNUNET_NO);
1102     return;
1103   }
1104   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker, quota);
1105   if (0 != ntohl (quota.value__))
1106     return;
1107 #if DEBUG_TRANSPORT
1108   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting peer `%4s' due to `%s'\n",
1109               GNUNET_i2s (&n->id), "SET_QUOTA");
1110 #endif
1111   if (GNUNET_YES == n->is_connected)
1112     GNUNET_STATISTICS_update (GST_stats,
1113                               gettext_noop ("# disconnects due to quota of 0"), 1,
1114                               GNUNET_NO);
1115   disconnect_neighbour (n);
1116 }
1117
1118
1119 /**
1120  * Closure for the neighbours_iterate function.
1121  */
1122 struct IteratorContext
1123 {
1124   /**
1125    * Function to call on each connected neighbour.
1126    */
1127   GST_NeighbourIterator cb;
1128
1129   /**
1130    * Closure for 'cb'.
1131    */
1132   void *cb_cls;
1133 };
1134
1135
1136 /**
1137  * Call the callback from the closure for each connected neighbour.
1138  *
1139  * @param cls the 'struct IteratorContext'
1140  * @param key the hash of the public key of the neighbour
1141  * @param value the 'struct NeighbourMapEntry'
1142  * @return GNUNET_OK (continue to iterate)
1143  */
1144 static int
1145 neighbours_iterate (void *cls, const GNUNET_HashCode * key, void *value)
1146 {
1147   struct IteratorContext *ic = cls;
1148   struct NeighbourMapEntry *n = value;
1149
1150   if (GNUNET_YES != n->is_connected)
1151     return GNUNET_OK;
1152
1153   GNUNET_assert (n->ats_count > 0);
1154   ic->cb (ic->cb_cls, &n->id, n->ats, n->ats_count, n->plugin_name, n->addr, n->addrlen);
1155   return GNUNET_OK;
1156 }
1157
1158
1159 /**
1160  * Iterate over all connected neighbours.
1161  *
1162  * @param cb function to call
1163  * @param cb_cls closure for cb
1164  */
1165 void
1166 GST_neighbours_iterate (GST_NeighbourIterator cb, void *cb_cls)
1167 {
1168   struct IteratorContext ic;
1169
1170   GNUNET_assert (neighbours != NULL);
1171
1172   ic.cb = cb;
1173   ic.cb_cls = cb_cls;
1174   GNUNET_CONTAINER_multihashmap_iterate (neighbours, &neighbours_iterate, &ic);
1175 }
1176
1177
1178 /**
1179  * If we have an active connection to the given target, it must be shutdown.
1180  *
1181  * @param target peer to disconnect from
1182  */
1183 void
1184 GST_neighbours_force_disconnect (const struct GNUNET_PeerIdentity *target)
1185 {
1186   struct NeighbourMapEntry *n;
1187   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1188   struct SessionDisconnectMessage disconnect_msg;
1189
1190   GNUNET_assert (neighbours != NULL);
1191
1192   n = lookup_neighbour (target);
1193   if (NULL == n)
1194     return;                     /* not active */
1195   if (GNUNET_YES == n->is_connected)
1196   {
1197     /* we're actually connected, send DISCONNECT message */
1198     disconnect_msg.header.size = htons (sizeof (struct SessionDisconnectMessage));
1199     disconnect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
1200     disconnect_msg.reserved = htonl (0);
1201     disconnect_msg.purpose.size = htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
1202                                          sizeof (struct GNUNET_TIME_AbsoluteNBO));
1203     disconnect_msg.purpose.purpose = htonl (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT);
1204     disconnect_msg.timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1205     GNUNET_assert (GNUNET_OK ==
1206                    GNUNET_CRYPTO_rsa_sign (GST_my_private_key,
1207                                            &disconnect_msg.purpose,
1208                                            &disconnect_msg.signature));
1209     papi = GST_plugins_find (n->plugin_name);
1210     if (papi != NULL)
1211       papi->send (papi->cls, target, (const void *) &disconnect_msg,
1212                   sizeof (disconnect_msg),
1213                   UINT32_MAX /* priority */ ,
1214                   GNUNET_TIME_UNIT_FOREVER_REL, n->session, n->addr, n->addrlen,
1215                   GNUNET_YES, NULL, NULL);
1216     GNUNET_STATISTICS_update (GST_stats,
1217                               gettext_noop ("# peers disconnected due to external request"), 1,
1218                               GNUNET_NO);
1219   }
1220   disconnect_neighbour (n);
1221 }
1222
1223
1224 /* end of file gnunet-service-transport_neighbours.c */