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