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