fixing https://www.gnunet.org/bugs/view.php?id=1867
[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-service-transport_blacklist.h"
35 #include "gnunet_constants.h"
36 #include "transport.h"
37
38
39 /**
40  * Size of the neighbour hash map.
41  */
42 #define NEIGHBOUR_TABLE_SIZE 256
43
44 /**
45  * How often must a peer violate bandwidth quotas before we start
46  * to simply drop its messages?
47  */
48 #define QUOTA_VIOLATION_DROP_THRESHOLD 10
49
50 /**
51  * How often do we send KEEPALIVE messages to each of our neighbours?
52  * (idle timeout is 5 minutes or 300 seconds, so with 90s interval we
53  * send 3 keepalives in each interval, so 3 messages would need to be
54  * lost in a row for a disconnect).
55  */
56 #define KEEPALIVE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 90)
57
58
59 #define ATS_RESPONSE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 3)
60
61
62 #define SETUP_CONNECTION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
63
64
65 /**
66  * Entry in neighbours.
67  */
68 struct NeighbourMapEntry;
69
70 /**
71  * Message a peer sends to another to indicate its
72  * preference for communicating via a particular
73  * session (and the desire to establish a real
74  * connection).
75  */
76 struct SessionConnectMessage
77 {
78   /**
79    * Header of type 'GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT'
80    */
81   struct GNUNET_MessageHeader header;
82
83   /**
84    * Always zero.
85    */
86   uint32_t reserved GNUNET_PACKED;
87
88   /**
89    * Absolute time at the sender.  Only the most recent connect
90    * message implies which session is preferred by the sender.
91    */
92   struct GNUNET_TIME_AbsoluteNBO timestamp;
93
94 };
95
96
97 struct SessionDisconnectMessage
98 {
99   /**
100    * Header of type 'GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT'
101    */
102   struct GNUNET_MessageHeader header;
103
104   /**
105    * Always zero.
106    */
107   uint32_t reserved GNUNET_PACKED;
108
109   /**
110    * Purpose of the signature.  Extends over the timestamp.
111    * Purpose should be GNUNET_SIGNATURE_PURPOSE_TRANSPORT_DISCONNECT.
112    */
113   struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
114
115   /**
116    * Absolute time at the sender.  Only the most recent connect
117    * message implies which session is preferred by the sender.
118    */
119   struct GNUNET_TIME_AbsoluteNBO timestamp;
120
121   /**
122    * Public key of the sender.
123    */
124   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded public_key;
125   
126   /**
127    * Signature of the peer that sends us the disconnect.  Only
128    * valid if the timestamp is AFTER the timestamp from the
129    * corresponding 'CONNECT' message.
130    */
131   struct GNUNET_CRYPTO_RsaSignature signature;
132
133 };
134
135
136 /**
137  * For each neighbour we keep a list of messages
138  * that we still want to transmit to the neighbour.
139  */
140 struct MessageQueue
141 {
142
143   /**
144    * This is a doubly linked list.
145    */
146   struct MessageQueue *next;
147
148   /**
149    * This is a doubly linked list.
150    */
151   struct MessageQueue *prev;
152
153   /**
154    * Once this message is actively being transmitted, which
155    * neighbour is it associated with?
156    */
157   struct NeighbourMapEntry *n;
158
159   /**
160    * Function to call once we're done.
161    */
162   GST_NeighbourSendContinuation cont;
163
164   /**
165    * Closure for 'cont'
166    */
167   void *cont_cls;
168
169   /**
170    * The message(s) we want to transmit, GNUNET_MessageHeader(s)
171    * stuck together in memory.  Allocated at the end of this struct.
172    */
173   const char *message_buf;
174
175   /**
176    * Size of the message buf
177    */
178   size_t message_buf_size;
179
180   /**
181    * At what time should we fail?
182    */
183   struct GNUNET_TIME_Absolute timeout;
184
185 };
186
187 enum State
188 {
189     /* fresh peer or completely disconnected */
190     S_NOT_CONNECTED = 0,
191     /* sent CONNECT message to other peer, waiting for CONNECT_ACK */
192     S_CONNECT_SENT = 1,
193     /* received CONNECT message to other peer, sending CONNECT_ACK */
194     S_CONNECT_RECV = 4,
195     /* sent CONNECT_ACK message to other peer, wait for ACK or payload */
196     S_CONNECT_RECV_ACK_SENT = 8,
197     /* received ACK or payload */
198     S_CONNECTED = 16,
199     /* Disconnect in progress */
200     S_DISCONNECT = 32
201 };
202
203 /**
204  * Entry in neighbours.
205  */
206 struct NeighbourMapEntry
207 {
208
209   /**
210    * Head of list of messages we would like to send to this peer;
211    * must contain at most one message per client.
212    */
213   struct MessageQueue *messages_head;
214
215   /**
216    * Tail of list of messages we would like to send to this peer; must
217    * contain at most one message per client.
218    */
219   struct MessageQueue *messages_tail;
220
221   /**
222    * Performance data for the peer.
223    */
224   //struct GNUNET_ATS_Information *ats;
225
226   /**
227    * Are we currently trying to send a message? If so, which one?
228    */
229   struct MessageQueue *is_active;
230
231   /**
232    * Active session for communicating with the peer.
233    */
234   struct Session *session;
235
236   /**
237    * Name of the plugin we currently use.
238    */
239   char *plugin_name;
240
241   /**
242    * Address used for communicating with the peer, NULL for inbound connections.
243    */
244   void *addr;
245
246   /**
247    * Number of bytes in 'addr'.
248    */
249   size_t addrlen;
250
251   /**
252    * Identity of this neighbour.
253    */
254   struct GNUNET_PeerIdentity id;
255
256   /**
257    * ID of task scheduled to run when this peer is about to
258    * time out (will free resources associated with the peer).
259    */
260   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
261
262   /**
263    * ID of task scheduled to send keepalives.
264    */
265   GNUNET_SCHEDULER_TaskIdentifier keepalive_task;
266
267   /**
268    * ID of task scheduled to run when we should try transmitting
269    * the head of the message queue.
270    */
271   GNUNET_SCHEDULER_TaskIdentifier transmission_task;
272
273   /**
274    * Tracker for inbound bandwidth.
275    */
276   struct GNUNET_BANDWIDTH_Tracker in_tracker;
277
278   /**
279    * Inbound bandwidth from ATS, activated when connection is up
280    */
281   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in;
282
283   /**
284    * Inbound bandwidth from ATS, activated when connection is up
285    */
286   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out;
287
288   /**
289    * Timestamp of the 'SESSION_CONNECT' message we got from the other peer
290    */
291   struct GNUNET_TIME_Absolute connect_ts;
292
293   /**
294    * Timeout for ATS
295    * We asked ATS for a new address for this peer
296    */
297   GNUNET_SCHEDULER_TaskIdentifier ats_suggest;
298
299   /**
300    * Task the resets the peer state after due to an pending
301    * unsuccessful connection setup
302    */
303   GNUNET_SCHEDULER_TaskIdentifier state_reset;
304
305   /**
306    * How often has the other peer (recently) violated the inbound
307    * traffic limit?  Incremented by 10 per violation, decremented by 1
308    * per non-violation (for each time interval).
309    */
310   unsigned int quota_violation_count;
311
312
313   /**
314    * The current state of the peer
315    * Element of enum State
316    */
317   int state;
318
319 };
320
321
322 /**
323  * All known neighbours and their HELLOs.
324  */
325 static struct GNUNET_CONTAINER_MultiHashMap *neighbours;
326
327 /**
328  * Closure for connect_notify_cb and disconnect_notify_cb
329  */
330 static void *callback_cls;
331
332 /**
333  * Function to call when we connected to a neighbour.
334  */
335 static GNUNET_TRANSPORT_NotifyConnect connect_notify_cb;
336
337 /**
338  * Function to call when we disconnected from a neighbour.
339  */
340 static GNUNET_TRANSPORT_NotifyDisconnect disconnect_notify_cb;
341
342 /**
343  * counter for connected neighbours
344  */
345 static int neighbours_connected;
346
347 /**
348  * Lookup a neighbour entry in the neighbours hash map.
349  *
350  * @param pid identity of the peer to look up
351  * @return the entry, NULL if there is no existing record
352  */
353 static struct NeighbourMapEntry *
354 lookup_neighbour (const struct GNUNET_PeerIdentity *pid)
355 {
356   return GNUNET_CONTAINER_multihashmap_get (neighbours, &pid->hashPubKey);
357 }
358
359 #define change_state(n, state, ...) change (n, state, __LINE__)
360
361 static int
362 is_connecting (struct NeighbourMapEntry * n)
363 {
364   if ((n->state > S_NOT_CONNECTED) && (n->state < S_CONNECTED))
365     return GNUNET_YES;
366   return GNUNET_NO;
367 }
368
369 static int
370 is_connected (struct NeighbourMapEntry * n)
371 {
372   if (n->state == S_CONNECTED)
373     return GNUNET_YES;
374   return GNUNET_NO;
375 }
376
377 static int
378 is_disconnecting (struct NeighbourMapEntry * n)
379 {
380   if (n->state == S_DISCONNECT)
381     return GNUNET_YES;
382   return GNUNET_NO;
383 }
384
385 static const char *
386 print_state (int state)
387 {
388   switch (state) {
389     case S_CONNECTED:
390         return "S_CONNECTED";
391       break;
392     case S_CONNECT_RECV:
393       return "S_CONNECT_RECV";
394       break;
395     case S_CONNECT_RECV_ACK_SENT:
396       return"S_CONNECT_RECV_ACK_SENT";
397       break;
398     case S_CONNECT_SENT:
399       return "S_CONNECT_SENT";
400       break;
401     case S_DISCONNECT:
402       return "S_DISCONNECT";
403       break;
404     case S_NOT_CONNECTED:
405       return "S_NOT_CONNECTED";
406       break;
407     default:
408       GNUNET_break (0);
409       break;
410   }
411   return NULL;
412 }
413
414 static int
415 change (struct NeighbourMapEntry * n, int state, int line);
416
417 static void
418 ats_suggest_cancel (void *cls,
419     const struct GNUNET_SCHEDULER_TaskContext *tc);
420
421 static void
422 reset_task (void *cls,
423             const struct GNUNET_SCHEDULER_TaskContext *tc)
424 {
425   struct NeighbourMapEntry * n = cls;
426
427   n->state_reset = GNUNET_SCHEDULER_NO_TASK;
428
429 #if DEBUG_TRANSPORT
430   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
431       "Connection to peer `%s' %s failed in state `%s', resetting connection attempt \n",
432       GNUNET_i2s (&n->id), GST_plugins_a2s(n->plugin_name, n->addr, n->addrlen), print_state(n->state));
433 #endif
434   GNUNET_STATISTICS_update (GST_stats,
435                             gettext_noop ("# failed connection attempts due to timeout"),
436                             1,
437                             GNUNET_NO);
438
439   /* resetting state */
440   n->state = S_NOT_CONNECTED;
441
442   /* destroying address */
443   GNUNET_ATS_address_destroyed (GST_ats,
444                                 &n->id,
445                                 n->plugin_name,
446                                 n->addr,
447                                 n->addrlen,
448                                 NULL);
449
450   /* request new address */
451   if (n->ats_suggest != GNUNET_SCHEDULER_NO_TASK)
452     GNUNET_SCHEDULER_cancel(n->ats_suggest);
453   n->ats_suggest = GNUNET_SCHEDULER_add_delayed (ATS_RESPONSE_TIMEOUT, ats_suggest_cancel, n);
454   GNUNET_ATS_suggest_address(GST_ats, &n->id);
455 }
456
457 static int
458 change (struct NeighbourMapEntry * n, int state, int line)
459 {
460   char * old = strdup(print_state(n->state));
461   char * new = strdup(print_state(state));
462
463   /* allowed transitions */
464   int allowed = GNUNET_NO;
465   switch (n->state) {
466   case S_NOT_CONNECTED:
467     if ((state == S_CONNECT_RECV) || (state == S_CONNECT_SENT) ||
468         (state == S_DISCONNECT))
469     {
470       allowed = GNUNET_YES;
471
472       /* Schedule reset task */
473       if ((state == S_CONNECT_RECV) || (state == S_CONNECT_SENT) )
474       {
475         GNUNET_assert (n->state_reset == GNUNET_SCHEDULER_NO_TASK);
476         n->state_reset = GNUNET_SCHEDULER_add_delayed (SETUP_CONNECTION_TIMEOUT, &reset_task, n);
477       }
478
479       break;
480     }
481     break;
482   case S_CONNECT_RECV:
483     if ((state == S_NOT_CONNECTED) || (state == S_DISCONNECT) ||
484         (state == S_CONNECTED) || /* FIXME SENT -> RECV ISSUE!*/ (state == S_CONNECT_SENT))
485     {
486       if ((state == S_CONNECTED) || (state == S_DISCONNECT) || (state == S_NOT_CONNECTED))
487       {
488 #if DEBUG_TRANSPORT
489         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
490             "Removed reset task for peer `%s' %s failed in state transition `%s' -> `%s' \n",
491             GNUNET_i2s (&n->id), GST_plugins_a2s(n->plugin_name, n->addr, n->addrlen), print_state(n->state), print_state(state));
492 #endif
493         GNUNET_assert (n->state_reset != GNUNET_SCHEDULER_NO_TASK);
494         GNUNET_SCHEDULER_cancel (n->state_reset);
495         n->state_reset = GNUNET_SCHEDULER_NO_TASK;
496       }
497
498       allowed = GNUNET_YES;
499       break;
500     }
501     break;
502   case S_CONNECT_SENT:
503     if ((state == S_NOT_CONNECTED) || (state == S_CONNECTED) ||
504         (state == S_DISCONNECT) || /* FIXME SENT -> RECV ISSUE!*/ (state == S_CONNECT_RECV))
505     {
506       if ((state == S_CONNECTED) || (state == S_DISCONNECT) || (state == S_NOT_CONNECTED))
507       {
508 #if DEBUG_TRANSPORT
509         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
510             "Removed reset task for peer `%s' %s failed in state transition `%s' -> `%s' \n",
511             GNUNET_i2s (&n->id), GST_plugins_a2s(n->plugin_name, n->addr, n->addrlen), print_state(n->state), print_state(state));
512 #endif
513         GNUNET_assert (n->state_reset != GNUNET_SCHEDULER_NO_TASK);
514         GNUNET_SCHEDULER_cancel (n->state_reset);
515         n->state_reset = GNUNET_SCHEDULER_NO_TASK;
516       }
517
518       allowed = GNUNET_YES;
519       break;
520     }
521     break;
522   case S_CONNECTED:
523     if (state == S_DISCONNECT)
524     {
525       allowed = GNUNET_YES;
526       break;
527     }
528     break;
529   case S_DISCONNECT:
530     /*
531     if (state == S_NOT_CONNECTED)
532     {
533       allowed = GNUNET_YES;
534       break;
535     }*/
536     break;
537   default:
538     GNUNET_break (0);
539     break;
540
541   }
542
543   if (allowed == GNUNET_NO)
544   {
545     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
546         "Illegal state transition from `%s' to `%s' in line %u \n",
547         old, new, line);
548     GNUNET_break (0);
549     GNUNET_free (old);
550     GNUNET_free (new);
551     return GNUNET_SYSERR;
552   }
553
554   n->state = state;
555 #if DEBUG_TRANSPORT
556   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "State for neighbour `%s' %X changed from `%s' to `%s' in line %u\n",
557       GNUNET_i2s (&n->id), n, old, new, line);
558 #endif
559   GNUNET_free (old);
560   GNUNET_free (new);
561   return GNUNET_OK;
562 }
563
564 static ssize_t
565 send_with_plugin ( const struct GNUNET_PeerIdentity * target,
566     const char *msgbuf,
567     size_t msgbuf_size,
568     uint32_t priority,
569     struct GNUNET_TIME_Relative timeout,
570     struct Session * session,
571     const char * plugin_name,
572     const void *addr,
573     size_t addrlen,
574     int force_address,
575     GNUNET_TRANSPORT_TransmitContinuation cont,
576     void *cont_cls)
577
578 {
579   struct GNUNET_TRANSPORT_PluginFunctions *papi;
580   size_t ret = GNUNET_SYSERR;
581
582   GNUNET_assert (plugin_name != NULL);
583   papi = GST_plugins_find (plugin_name);
584   if (papi == NULL)
585   {
586     if (cont != NULL)
587       cont (cont_cls, target, GNUNET_SYSERR);
588     return GNUNET_SYSERR;
589   }
590
591   ret = papi->send (papi->cls,
592       target,
593       msgbuf, msgbuf_size,
594       0,
595       timeout,
596       session,
597       addr, addrlen,
598       GNUNET_YES,
599       cont, cont_cls);
600
601   if (ret == -1)
602   {
603     if (cont != NULL)
604       cont (cont_cls, target, GNUNET_SYSERR);
605   }
606   return ret;
607 }
608
609 /**
610  * Task invoked to start a transmission to another peer.
611  *
612  * @param cls the 'struct NeighbourMapEntry'
613  * @param tc scheduler context
614  */
615 static void
616 transmission_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
617
618
619 /**
620  * We're done with our transmission attempt, continue processing.
621  *
622  * @param cls the 'struct MessageQueue' of the message
623  * @param receiver intended receiver
624  * @param success whether it worked or not
625  */
626 static void
627 transmit_send_continuation (void *cls,
628                             const struct GNUNET_PeerIdentity *receiver,
629                             int success)
630 {
631   struct MessageQueue *mq;
632   struct NeighbourMapEntry *n;
633
634   mq = cls;
635   n = mq->n;
636   if (NULL != n)
637   {
638     GNUNET_assert (n->is_active == mq);
639     n->is_active = NULL;
640     if (success == GNUNET_YES)
641     {
642       GNUNET_assert (n->transmission_task == GNUNET_SCHEDULER_NO_TASK);
643       n->transmission_task = GNUNET_SCHEDULER_add_now (&transmission_task, n);
644     }
645   }
646 #if DEBUG_TRANSPORT
647   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending message of type %u was %s\n",
648               ntohs (((struct GNUNET_MessageHeader *) mq->message_buf)->type),
649               (success == GNUNET_OK) ? "successful" : "FAILED");
650 #endif
651   if (NULL != mq->cont)
652     mq->cont (mq->cont_cls, success);
653   GNUNET_free (mq);
654 }
655
656
657 /**
658  * Check the ready list for the given neighbour and if a plugin is
659  * ready for transmission (and if we have a message), do so!
660  *
661  * @param n target peer for which to transmit
662  */
663 static void
664 try_transmission_to_peer (struct NeighbourMapEntry *n)
665 {
666   struct MessageQueue *mq;
667   struct GNUNET_TIME_Relative timeout;
668   ssize_t ret;
669
670   if (n->is_active != NULL)
671   {
672     GNUNET_break (0);
673     return;                     /* transmission already pending */
674   }
675   if (n->transmission_task != GNUNET_SCHEDULER_NO_TASK)
676   {
677     GNUNET_break (0);
678     return;                     /* currently waiting for bandwidth */
679   }
680   while (NULL != (mq = n->messages_head))
681   {
682     timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
683     if (timeout.rel_value > 0)
684       break;
685     GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
686     n->is_active = mq;
687     mq->n = n;
688     transmit_send_continuation (mq, &n->id, GNUNET_SYSERR);     /* timeout */
689   }
690   if (NULL == mq)
691     return;                     /* no more messages */
692
693   if (GST_plugins_find (n->plugin_name) == NULL)
694   {
695     GNUNET_break (0);
696     return;
697   }
698   GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
699   n->is_active = mq;
700   mq->n = n;
701
702   if  ((n->session == NULL) && (n->addr == NULL) && (n->addrlen == 0))
703   {
704     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "No address for peer `%s'\n",
705                 GNUNET_i2s (&n->id));
706     transmit_send_continuation (mq, &n->id, GNUNET_SYSERR);
707     GNUNET_assert (n->transmission_task == GNUNET_SCHEDULER_NO_TASK);
708     n->transmission_task = GNUNET_SCHEDULER_add_now (&transmission_task, n);
709     return;
710   }
711
712   ret = send_with_plugin (&n->id,
713                           mq->message_buf, mq->message_buf_size, 0,
714                           timeout,
715                           n->session, n->plugin_name, n->addr, n->addrlen,
716                           GNUNET_YES,
717                           &transmit_send_continuation, mq);
718   if (ret == -1)
719   {
720     /* failure, but 'send' would not call continuation in this case,
721      * so we need to do it here! */
722     transmit_send_continuation (mq, &n->id, GNUNET_SYSERR);
723   }
724
725 }
726
727
728 /**
729  * Task invoked to start a transmission to another peer.
730  *
731  * @param cls the 'struct NeighbourMapEntry'
732  * @param tc scheduler context
733  */
734 static void
735 transmission_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
736 {
737   struct NeighbourMapEntry *n = cls;
738   GNUNET_assert (NULL != lookup_neighbour(&n->id));
739   n->transmission_task = GNUNET_SCHEDULER_NO_TASK;
740   try_transmission_to_peer (n);
741 }
742
743
744 /**
745  * Initialize the neighbours subsystem.
746  *
747  * @param cls closure for callbacks
748  * @param connect_cb function to call if we connect to a peer
749  * @param disconnect_cb function to call if we disconnect from a peer
750  */
751 void
752 GST_neighbours_start (void *cls, GNUNET_TRANSPORT_NotifyConnect connect_cb,
753                       GNUNET_TRANSPORT_NotifyDisconnect disconnect_cb)
754 {
755   callback_cls = cls;
756   connect_notify_cb = connect_cb;
757   disconnect_notify_cb = disconnect_cb;
758   neighbours = GNUNET_CONTAINER_multihashmap_create (NEIGHBOUR_TABLE_SIZE);
759 }
760
761
762 static void
763 send_disconnect_cont (void *cls,
764     const struct GNUNET_PeerIdentity * target,
765     int result)
766 {
767 #if DEBUG_TRANSPORT
768   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending DISCONNECT message to peer `%4s': %i\n",
769               GNUNET_i2s (target), result);
770 #endif
771 }
772
773
774 static int
775 send_disconnect (const struct GNUNET_PeerIdentity * target,
776                  const char *plugin_name,
777                  const char *sender_address, uint16_t sender_address_len,
778                  struct Session *session)
779 {
780   size_t ret;
781   struct SessionDisconnectMessage disconnect_msg;
782
783 #if DEBUG_TRANSPORT
784   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending DISCONNECT message to peer `%4s'\n",
785               GNUNET_i2s (target));
786 #endif
787
788   disconnect_msg.header.size = htons (sizeof (struct SessionDisconnectMessage));
789   disconnect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT);
790   disconnect_msg.reserved = htonl (0);
791   disconnect_msg.purpose.size = htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
792                                        sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
793                                        sizeof (struct GNUNET_TIME_AbsoluteNBO) );
794   disconnect_msg.purpose.purpose = htonl (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT);
795   disconnect_msg.timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
796   disconnect_msg.public_key = GST_my_public_key;
797   GNUNET_assert (GNUNET_OK ==
798                  GNUNET_CRYPTO_rsa_sign (GST_my_private_key,
799                                          &disconnect_msg.purpose,
800                                          &disconnect_msg.signature));
801
802   ret = send_with_plugin(target,
803                          (const char *) &disconnect_msg, sizeof (disconnect_msg),
804                          UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_REL,
805                          session, plugin_name, sender_address,  sender_address_len,
806                          GNUNET_YES, &send_disconnect_cont, NULL);
807
808   if (ret == GNUNET_SYSERR)
809     return GNUNET_SYSERR;
810
811   GNUNET_STATISTICS_update (GST_stats,
812                             gettext_noop ("# peers disconnected due to external request"), 1,
813                             GNUNET_NO);
814   return GNUNET_OK;
815 }
816
817 /**
818  * Disconnect from the given neighbour, clean up the record.
819  *
820  * @param n neighbour to disconnect from
821  */
822 static void
823 disconnect_neighbour (struct NeighbourMapEntry *n)
824 {
825   struct MessageQueue *mq;
826   int was_connected = is_connected(n);
827
828   /* send DISCONNECT MESSAGE */
829   if (is_connected(n) || is_connecting(n))
830   {
831     if (GNUNET_OK == send_disconnect(&n->id, n->plugin_name, n->addr, n->addrlen, n->session))
832       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sent DISCONNECT_MSG to `%s'\n",
833                   GNUNET_i2s (&n->id));
834     else
835       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Could not send DISCONNECT_MSG to `%s'\n",
836                   GNUNET_i2s (&n->id));
837   }
838
839
840   if (is_disconnecting(n))
841     return;
842   change_state (n, S_DISCONNECT);
843
844   while (NULL != (mq = n->messages_head))
845   {
846     GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
847     if (NULL != mq->cont)
848       mq->cont (mq->cont_cls, GNUNET_SYSERR);
849     GNUNET_free (mq);
850   }
851   if (NULL != n->is_active)
852   {
853     n->is_active->n = NULL;
854     n->is_active = NULL;
855   }
856   if (was_connected)
857   {
858     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != n->keepalive_task);
859     GNUNET_SCHEDULER_cancel (n->keepalive_task);
860     n->keepalive_task = GNUNET_SCHEDULER_NO_TASK;  
861     GNUNET_assert (neighbours_connected > 0);
862     neighbours_connected--;
863     GNUNET_STATISTICS_update (GST_stats, gettext_noop ("# peers connected"), -1,
864                               GNUNET_NO);
865     disconnect_notify_cb (callback_cls, &n->id);
866   }
867   GNUNET_assert (GNUNET_YES ==
868                  GNUNET_CONTAINER_multihashmap_remove (neighbours,
869                                                        &n->id.hashPubKey, n));
870   if (GNUNET_SCHEDULER_NO_TASK != n->ats_suggest)
871   {
872     GNUNET_SCHEDULER_cancel (n->ats_suggest);
873     n->ats_suggest = GNUNET_SCHEDULER_NO_TASK;
874   }
875   if (GNUNET_SCHEDULER_NO_TASK != n->timeout_task)
876   {
877     GNUNET_SCHEDULER_cancel (n->timeout_task);
878     n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
879   }
880   if (GNUNET_SCHEDULER_NO_TASK != n->transmission_task)
881   {
882     GNUNET_SCHEDULER_cancel (n->transmission_task);
883     n->transmission_task = GNUNET_SCHEDULER_NO_TASK;
884   }
885   if (NULL != n->plugin_name)
886   {
887     GNUNET_free (n->plugin_name);
888     n->plugin_name = NULL;
889   }
890   if (NULL != n->addr)
891   {
892     GNUNET_free (n->addr);
893     n->addr = NULL;
894     n->addrlen = 0;
895   }
896   n->session = NULL;
897   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Deleting peer `%4s', %X\n",
898               GNUNET_i2s (&n->id), n);
899   GNUNET_free (n);
900 }
901
902
903 /**
904  * Peer has been idle for too long. Disconnect.
905  *
906  * @param cls the 'struct NeighbourMapEntry' of the neighbour that went idle
907  * @param tc scheduler context
908  */
909 static void
910 neighbour_timeout_task (void *cls,
911                         const struct GNUNET_SCHEDULER_TaskContext *tc)
912 {
913   struct NeighbourMapEntry *n = cls;
914
915   n->timeout_task = GNUNET_SCHEDULER_NO_TASK;
916
917   GNUNET_STATISTICS_update (GST_stats,
918                             gettext_noop ("# peers disconnected due to timeout"), 1,
919                             GNUNET_NO);
920   disconnect_neighbour (n);
921 }
922
923
924 /**
925  * Send another keepalive message.
926  *
927  * @param cls the 'struct NeighbourMapEntry' of the neighbour that went idle
928  * @param tc scheduler context
929  */
930 static void
931 neighbour_keepalive_task (void *cls,
932                           const struct GNUNET_SCHEDULER_TaskContext *tc)
933 {
934   struct NeighbourMapEntry *n = cls;
935   struct GNUNET_MessageHeader m;
936
937   n->keepalive_task = GNUNET_SCHEDULER_add_delayed (KEEPALIVE_FREQUENCY,
938                                                     &neighbour_keepalive_task,
939                                                     n);
940   GNUNET_assert (is_connected(n));
941   GNUNET_STATISTICS_update (GST_stats,
942                             gettext_noop ("# keepalives sent"), 1,
943                             GNUNET_NO);
944   m.size = htons (sizeof (struct GNUNET_MessageHeader));
945   m.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE);
946
947   send_with_plugin(&n->id, (const void *) &m,
948                    sizeof (m),
949                    UINT32_MAX /* priority */ ,
950                    GNUNET_TIME_UNIT_FOREVER_REL,
951                    n->session, n->plugin_name, n->addr, n->addrlen,
952                    GNUNET_YES, NULL, NULL);
953 }
954
955
956 /**
957  * Disconnect from the given neighbour.
958  *
959  * @param cls unused
960  * @param key hash of neighbour's public key (not used)
961  * @param value the 'struct NeighbourMapEntry' of the neighbour
962  */
963 static int
964 disconnect_all_neighbours (void *cls, const GNUNET_HashCode * key, void *value)
965 {
966   struct NeighbourMapEntry *n = value;
967
968 #if DEBUG_TRANSPORT
969   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting peer `%4s', %s\n",
970               GNUNET_i2s (&n->id), "SHUTDOWN_TASK");
971 #endif
972   if (is_connected(n))
973     GNUNET_STATISTICS_update (GST_stats,
974                               gettext_noop ("# peers disconnected due to global disconnect"), 1,
975                               GNUNET_NO);
976   disconnect_neighbour (n);
977   return GNUNET_OK;
978 }
979
980
981 static void
982 ats_suggest_cancel (void *cls,
983     const struct GNUNET_SCHEDULER_TaskContext *tc)
984 {
985   struct NeighbourMapEntry *n = cls;
986
987   n->ats_suggest = GNUNET_SCHEDULER_NO_TASK;
988
989   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
990               " ATS did not suggested address to connect to peer `%s'\n",
991               GNUNET_i2s (&n->id));
992
993   disconnect_neighbour(n);
994 }
995
996
997 /**
998  * Cleanup the neighbours subsystem.
999  */
1000 void
1001 GST_neighbours_stop ()
1002 {
1003   GNUNET_assert (neighbours != NULL);
1004
1005   GNUNET_CONTAINER_multihashmap_iterate (neighbours, &disconnect_all_neighbours,
1006                                          NULL);
1007   GNUNET_CONTAINER_multihashmap_destroy (neighbours);
1008   GNUNET_assert (neighbours_connected == 0);
1009   neighbours = NULL;
1010   callback_cls = NULL;
1011   connect_notify_cb = NULL;
1012   disconnect_notify_cb = NULL;
1013 }
1014
1015
1016 /**
1017  * We tried to send a SESSION_CONNECT message to another peer.  If this
1018  * succeeded, we change the state.  If it failed, we should tell
1019  * ATS to not use this address anymore (until it is re-validated).
1020  *
1021  * @param cls the 'struct NeighbourMapEntry'
1022  * @param success GNUNET_OK on success
1023  */
1024 static void
1025 send_connect_continuation (void *cls,
1026       const struct GNUNET_PeerIdentity * target,
1027       int success)
1028
1029 {
1030   struct NeighbourMapEntry *n = cls;
1031
1032   GNUNET_assert (n != NULL);
1033   GNUNET_assert (!is_connected(n));
1034
1035   if (is_disconnecting(n))
1036     return; /* neighbour is going away */
1037
1038   if (GNUNET_YES != success)
1039   {
1040 #if DEBUG_TRANSPORT
1041     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1042               "Failed to send CONNECT_MSG to peer `%4s' with plugin `%s' address '%s' session %X, asking ATS for new address \n",
1043               GNUNET_i2s (&n->id), n->plugin_name,
1044               (n->addrlen == 0) ? "<inbound>" : GST_plugins_a2s (n->plugin_name,
1045                                                                   n->addr,
1046                                                                   n->addrlen),
1047               n->session);
1048 #endif
1049
1050     GNUNET_ATS_address_destroyed (GST_ats,
1051                                   &n->id,
1052                                   n->plugin_name, 
1053                                   n->addr,
1054                                   n->addrlen,
1055                                   NULL);
1056
1057     change_state(n, S_NOT_CONNECTED);
1058
1059     if (n->ats_suggest!= GNUNET_SCHEDULER_NO_TASK)
1060       GNUNET_SCHEDULER_cancel(n->ats_suggest);
1061     n->ats_suggest = GNUNET_SCHEDULER_add_delayed (ATS_RESPONSE_TIMEOUT, ats_suggest_cancel, n);
1062     GNUNET_ATS_suggest_address(GST_ats, &n->id);
1063     return;
1064   }
1065
1066
1067 }
1068
1069
1070 /**
1071  * We tried to switch addresses with an peer already connected. If it failed,
1072  * we should tell ATS to not use this address anymore (until it is re-validated).
1073  *
1074  * @param cls the 'struct NeighbourMapEntry'
1075  * @param success GNUNET_OK on success
1076  */
1077 static void
1078 send_switch_address_continuation (void *cls,
1079       const struct GNUNET_PeerIdentity * target,
1080       int success)
1081
1082 {
1083   struct NeighbourMapEntry *n = cls;
1084
1085   GNUNET_assert (n != NULL);
1086   if (is_disconnecting(n))
1087     return; /* neighbour is going away */
1088
1089   GNUNET_assert (n->state == S_CONNECTED);
1090   if (GNUNET_YES != success)
1091   {
1092 #if DEBUG_TRANSPORT
1093     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1094               "Failed to switch connected peer `%s' to plugin `%s' address '%s' session %X, asking ATS for new address \n",
1095               GNUNET_i2s (&n->id), n->plugin_name,
1096               (n->addrlen == 0) ? "<inbound>" : GST_plugins_a2s (n->plugin_name,
1097                                                                   n->addr,
1098                                                                   n->addrlen),
1099               n->session);
1100 #endif
1101
1102     GNUNET_ATS_address_destroyed (GST_ats,
1103                                   &n->id,
1104                                   n->plugin_name,
1105                                   n->addr,
1106                                   n->addrlen,
1107                                   NULL);
1108
1109     if (n->ats_suggest != GNUNET_SCHEDULER_NO_TASK)
1110       GNUNET_SCHEDULER_cancel(n->ats_suggest);
1111     n->ats_suggest = GNUNET_SCHEDULER_add_delayed (ATS_RESPONSE_TIMEOUT, ats_suggest_cancel, n);
1112     GNUNET_ATS_suggest_address(GST_ats, &n->id);
1113     return;
1114   }
1115 }
1116
1117 /**
1118  * We tried to send a SESSION_CONNECT message to another peer.  If this
1119  * succeeded, we change the state.  If it failed, we should tell
1120  * ATS to not use this address anymore (until it is re-validated).
1121  *
1122  * @param cls the 'struct NeighbourMapEntry'
1123  * @param success GNUNET_OK on success
1124  */
1125 static void
1126 send_connect_ack_continuation (void *cls,
1127       const struct GNUNET_PeerIdentity * target,
1128       int success)
1129
1130 {
1131   struct NeighbourMapEntry *n = cls;
1132
1133   GNUNET_assert (n != NULL);
1134
1135   if (GNUNET_YES == success)
1136     return; /* sending successful */
1137
1138   /* sending failed, ask for next address  */
1139 #if DEBUG_TRANSPORT
1140     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1141               "Failed to send CONNECT_MSG to peer `%4s' with plugin `%s' address '%s' session %X, asking ATS for new address \n",
1142               GNUNET_i2s (&n->id), n->plugin_name,
1143               (n->addrlen == 0) ? "<inbound>" : GST_plugins_a2s (n->plugin_name,
1144                                                                   n->addr,
1145                                                                   n->addrlen),
1146               n->session);
1147 #endif
1148     change_state(n, S_NOT_CONNECTED);
1149
1150     GNUNET_ATS_address_destroyed (GST_ats,
1151                                   &n->id,
1152                                   n->plugin_name,
1153                                   n->addr,
1154                                   n->addrlen,
1155                                   NULL);
1156
1157     if (n->ats_suggest != GNUNET_SCHEDULER_NO_TASK)
1158       GNUNET_SCHEDULER_cancel(n->ats_suggest);
1159     n->ats_suggest = GNUNET_SCHEDULER_add_delayed (ATS_RESPONSE_TIMEOUT, ats_suggest_cancel, n);
1160     GNUNET_ATS_suggest_address(GST_ats, &n->id);
1161 }
1162
1163 /**
1164  * For an existing neighbour record, set the active connection to
1165  * the given address.
1166  *
1167  * @param peer identity of the peer to switch the address for
1168  * @param plugin_name name of transport that delivered the PONG
1169  * @param address address of the other peer, NULL if other peer
1170  *                       connected to us
1171  * @param address_len number of bytes in address
1172  * @param session session to use (or NULL)
1173  * @param ats performance data
1174  * @param ats_count number of entries in ats
1175  * @return GNUNET_YES if we are currently connected, GNUNET_NO if the
1176  *         connection is not up (yet)
1177  */
1178 int
1179 GST_neighbours_switch_to_address_3way (const struct GNUNET_PeerIdentity *peer,
1180                                   const char *plugin_name, const void *address,
1181                                   size_t address_len, struct Session *session,
1182                                   const struct GNUNET_ATS_Information
1183                                   *ats, uint32_t ats_count,
1184                                   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
1185                                   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out)
1186 {
1187   struct NeighbourMapEntry *n;
1188   struct SessionConnectMessage connect_msg;
1189   size_t msg_len;
1190   size_t ret;
1191
1192   GNUNET_assert (neighbours != NULL);
1193   n = lookup_neighbour (peer);
1194   if (NULL == n)
1195   {
1196     if (NULL == session)
1197       GNUNET_ATS_address_destroyed (GST_ats,
1198                                     peer,
1199                                     plugin_name, address,
1200                                     address_len, NULL);    
1201     return GNUNET_NO;
1202   }
1203
1204   if (n->ats_suggest != GNUNET_SCHEDULER_NO_TASK)
1205   {
1206     GNUNET_SCHEDULER_cancel(n->ats_suggest);
1207     n->ats_suggest = GNUNET_SCHEDULER_NO_TASK;
1208   }
1209
1210 #if DEBUG_TRANSPORT
1211   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1212               "ATS tells us to switch to plugin `%s' address '%s' session %X for %s peer `%s'\n",
1213               plugin_name,
1214               (address_len == 0) ? "<inbound>" : GST_plugins_a2s (plugin_name,
1215                                                                   address,
1216                                                                   address_len),
1217               session, (is_connected(n) ? "CONNECTED" : "NOT CONNECTED"),
1218               GNUNET_i2s (peer));
1219 #endif
1220
1221   // do not switch addresses just update quotas
1222   if (n != NULL)
1223   {
1224     if ((is_connected(n)) && (address_len == n->addrlen))
1225     {
1226       if ((0 == memcmp (address, n->addr, address_len)) &&
1227           (n->session == session))
1228       {
1229         struct QuotaSetMessage q_msg;
1230
1231 #if DEBUG_TRANSPORT
1232   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1233               "Sending outbound quota of %u Bps and inbound quota of % Bps for peer `%s' to all clients\n",
1234               ntohl (n->bandwidth_out.value__),
1235               ntohl (n->bandwidth_in.value__),
1236               GNUNET_i2s (peer));
1237 #endif
1238
1239         n->bandwidth_in = bandwidth_in;
1240         n->bandwidth_out = bandwidth_out;
1241         GST_neighbours_set_incoming_quota(&n->id, n->bandwidth_in);
1242
1243         q_msg.header.size = htons (sizeof (struct QuotaSetMessage));
1244         q_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA);
1245         q_msg.quota = n->bandwidth_out;
1246         q_msg.peer = (*peer);
1247         GST_clients_broadcast (&q_msg.header, GNUNET_NO);
1248         return GNUNET_NO;
1249       }
1250     }
1251   }
1252
1253   GNUNET_free_non_null (n->addr);
1254   n->addr = GNUNET_malloc (address_len);
1255   memcpy (n->addr, address, address_len);
1256   n->bandwidth_in = bandwidth_in;
1257   n->bandwidth_out = bandwidth_out;
1258   n->addrlen = address_len;
1259   n->session = session;
1260   GNUNET_free_non_null (n->plugin_name);
1261   n->plugin_name = GNUNET_strdup (plugin_name);
1262   GNUNET_SCHEDULER_cancel (n->timeout_task);
1263   n->timeout_task =
1264       GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1265                                     &neighbour_timeout_task, n);
1266
1267   if (n->state == S_DISCONNECT)
1268   {
1269     /* We are disconnecting, nothing to do here */
1270     return GNUNET_NO;
1271   }
1272   /* We are not connected/connecting and initiate a fresh connect */
1273   if (n->state == S_NOT_CONNECTED)
1274   {
1275     msg_len = sizeof (struct SessionConnectMessage);
1276     connect_msg.header.size = htons (msg_len);
1277     connect_msg.header.type =
1278         htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT);
1279     connect_msg.reserved = htonl (0);
1280     connect_msg.timestamp =
1281         GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1282
1283     change_state (n, S_CONNECT_SENT);
1284
1285     ret = send_with_plugin (peer, (const char *) &connect_msg, msg_len, UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_REL,
1286                             session, plugin_name, address, address_len,
1287                             GNUNET_YES, &send_connect_continuation, n);
1288
1289     return GNUNET_NO;
1290   }
1291   /* We received a CONNECT message and asked ATS for an address */
1292   else if (n->state == S_CONNECT_RECV)
1293   {
1294     msg_len = sizeof (struct SessionConnectMessage);
1295     connect_msg.header.size = htons (msg_len);
1296     connect_msg.header.type =
1297       htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT_ACK);
1298     connect_msg.reserved = htonl (0);
1299     connect_msg.timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1300
1301     ret = send_with_plugin(&n->id, (const void *) &connect_msg, msg_len, UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_REL,
1302                            session, plugin_name, address, address_len,
1303                            GNUNET_YES, &send_connect_ack_continuation, n);
1304     return GNUNET_NO;
1305   }
1306   /* connected peer is switching addresses */
1307   else if (n->state == S_CONNECTED)
1308   {
1309     msg_len = sizeof (struct SessionConnectMessage);
1310     connect_msg.header.size = htons (msg_len);
1311     connect_msg.header.type =
1312         htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT);
1313     connect_msg.reserved = htonl (0);
1314     connect_msg.timestamp =
1315         GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1316
1317     ret = send_with_plugin (peer, (const char *) &connect_msg, msg_len, UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_REL,
1318                             session, plugin_name, address, address_len,
1319                             GNUNET_YES, &send_switch_address_continuation, n);
1320     if (ret == GNUNET_SYSERR)
1321     {
1322       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1323                 "Failed to send CONNECT_MESSAGE to `%4s' using plugin `%s' address '%s' session %X\n",
1324                 GNUNET_i2s (peer), plugin_name,
1325                 (address_len == 0) ? "<inbound>" : GST_plugins_a2s (plugin_name,
1326                                                                     address,
1327                                                                     address_len),
1328                 session);
1329     }
1330     return GNUNET_NO;
1331   }
1332   else if (n->state == S_CONNECT_SENT)
1333   {
1334      return GNUNET_NO;
1335   }
1336   GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Invalid connection state to switch addresses %u \n", n->state);
1337   GNUNET_break_op (0);
1338   return GNUNET_NO;
1339 }
1340
1341
1342 /**
1343  * Create an entry in the neighbour map for the given peer
1344  * 
1345  * @param peer peer to create an entry for
1346  * @return new neighbour map entry
1347  */
1348 static struct NeighbourMapEntry *
1349 setup_neighbour (const struct GNUNET_PeerIdentity *peer)
1350 {
1351   struct NeighbourMapEntry *n;
1352
1353 #if DEBUG_TRANSPORT
1354   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1355               "Unknown peer `%s', creating new neighbour\n",
1356               GNUNET_i2s (peer));
1357 #endif
1358   n = GNUNET_malloc (sizeof (struct NeighbourMapEntry));
1359   n->id = *peer;
1360   n->state = S_NOT_CONNECTED;
1361   GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
1362                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
1363                                  MAX_BANDWIDTH_CARRY_S);
1364   n->timeout_task =
1365     GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1366                                   &neighbour_timeout_task, n);
1367   GNUNET_assert (GNUNET_OK ==
1368                  GNUNET_CONTAINER_multihashmap_put (neighbours,
1369                                                     &n->id.hashPubKey, n,
1370                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1371   return n;
1372 }
1373
1374
1375 /**
1376  * Try to create a connection to the given target (eventually).
1377  *
1378  * @param target peer to try to connect to
1379  */
1380 void
1381 GST_neighbours_try_connect (const struct GNUNET_PeerIdentity *target)
1382 {
1383   struct NeighbourMapEntry *n;
1384
1385   GNUNET_assert (neighbours != NULL);
1386 #if DEBUG_TRANSPORT
1387   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Trying to connect to peer `%s'\n",
1388               GNUNET_i2s (target));
1389 #endif
1390   GNUNET_assert (0 !=
1391                  memcmp (target, &GST_my_identity,
1392                          sizeof (struct GNUNET_PeerIdentity)));
1393   n = lookup_neighbour (target);
1394
1395   if (NULL != n)
1396   {
1397     if ((is_connected(n)) || (is_connecting(n)))
1398       return;                     /* already connecting or connected */
1399     if (is_disconnecting(n))
1400       change_state (n, S_NOT_CONNECTED);
1401   }
1402
1403
1404   if (n == NULL)
1405     n = setup_neighbour (target);
1406 #if DEBUG_TRANSPORT
1407   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1408               "Asking ATS for suggested address to connect to peer `%s'\n",
1409               GNUNET_i2s (&n->id));
1410 #endif
1411
1412    GNUNET_ATS_suggest_address (GST_ats, &n->id);
1413 }
1414
1415 /**
1416  * Test if we're connected to the given peer.
1417  *
1418  * @param target peer to test
1419  * @return GNUNET_YES if we are connected, GNUNET_NO if not
1420  */
1421 int
1422 GST_neighbours_test_connected (const struct GNUNET_PeerIdentity *target)
1423 {
1424   struct NeighbourMapEntry *n;
1425
1426   GNUNET_assert (neighbours != NULL);
1427
1428   n = lookup_neighbour (target);
1429
1430   if ((NULL == n) || (!is_connected(n)))
1431     return GNUNET_NO;           /* not connected */
1432   return GNUNET_YES;
1433 }
1434
1435
1436 /**
1437  * A session was terminated. Take note.
1438  *
1439  * @param peer identity of the peer where the session died
1440  * @param session session that is gone
1441  */
1442 void
1443 GST_neighbours_session_terminated (const struct GNUNET_PeerIdentity *peer,
1444                                    struct Session *session)
1445 {
1446   struct NeighbourMapEntry *n;
1447
1448   GNUNET_assert (neighbours != NULL);
1449
1450 #if DEBUG_TRANSPORT
1451   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1452               "Session %X to peer `%s' ended \n",
1453               session, GNUNET_i2s (peer));
1454 #endif
1455
1456   n = lookup_neighbour (peer);
1457   if (NULL == n)
1458     return;
1459   if (session != n->session)
1460     return;                     /* doesn't affect us */
1461
1462   n->session = NULL;
1463   GNUNET_free (n->addr);
1464   n->addr = NULL;
1465   n->addrlen = 0;
1466
1467   /* not connected anymore anyway, shouldn't matter */
1468   if ((!is_connected(n)) && (!is_connecting(n)))
1469     return;
1470
1471   /* We are connected, so ask ATS to switch addresses */
1472   GNUNET_SCHEDULER_cancel (n->timeout_task);
1473   n->timeout_task =
1474       GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_DISCONNECT_SESSION_TIMEOUT,
1475                                     &neighbour_timeout_task, n);
1476   /* try QUICKLY to re-establish a connection, reduce timeout! */
1477   if (n->ats_suggest != GNUNET_SCHEDULER_NO_TASK)
1478     GNUNET_SCHEDULER_cancel(n->ats_suggest);
1479   n->ats_suggest = GNUNET_SCHEDULER_add_delayed (ATS_RESPONSE_TIMEOUT, ats_suggest_cancel, n);
1480   GNUNET_ATS_suggest_address (GST_ats, peer);
1481 }
1482
1483
1484 /**
1485  * Transmit a message to the given target using the active connection.
1486  *
1487  * @param target destination
1488  * @param msg message to send
1489  * @param msg_size number of bytes in msg
1490  * @param timeout when to fail with timeout
1491  * @param cont function to call when done
1492  * @param cont_cls closure for 'cont'
1493  */
1494 void
1495 GST_neighbours_send (const struct GNUNET_PeerIdentity *target, const void *msg,
1496                      size_t msg_size, struct GNUNET_TIME_Relative timeout,
1497                      GST_NeighbourSendContinuation cont, void *cont_cls)
1498 {
1499   struct NeighbourMapEntry *n;
1500   struct MessageQueue *mq;
1501
1502   GNUNET_assert (neighbours != NULL);
1503
1504   n = lookup_neighbour (target);
1505   if ((n == NULL) || (!is_connected(n)))
1506   {
1507     GNUNET_STATISTICS_update (GST_stats,
1508                               gettext_noop
1509                               ("# messages not sent (no such peer or not connected)"),
1510                               1, GNUNET_NO);
1511 #if DEBUG_TRANSPORT
1512     if (n == NULL)
1513       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1514                   "Could not send message to peer `%s': unknown neighbour",
1515                   GNUNET_i2s (target));
1516     else if (!is_connected(n))
1517       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1518                   "Could not send message to peer `%s': not connected\n",
1519                   GNUNET_i2s (target));
1520 #endif
1521     if (NULL != cont)
1522       cont (cont_cls, GNUNET_SYSERR);
1523     return;
1524   }
1525
1526   if ((n->session == NULL) && (n->addr == NULL) && (n->addrlen ==0))
1527   {
1528     GNUNET_STATISTICS_update (GST_stats,
1529                               gettext_noop
1530                               ("# messages not sent (no such peer or not connected)"),
1531                               1, GNUNET_NO);
1532 #if DEBUG_TRANSPORT
1533       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1534                   "Could not send message to peer `%s': no address available\n",
1535                   GNUNET_i2s (target));
1536 #endif
1537
1538     if (NULL != cont)
1539       cont (cont_cls, GNUNET_SYSERR);
1540     return;
1541   }
1542
1543   GNUNET_assert (msg_size >= sizeof (struct GNUNET_MessageHeader));
1544   GNUNET_STATISTICS_update (GST_stats,
1545                             gettext_noop
1546                             ("# bytes in message queue for other peers"),
1547                             msg_size, GNUNET_NO);
1548   mq = GNUNET_malloc (sizeof (struct MessageQueue) + msg_size);
1549   mq->cont = cont;
1550   mq->cont_cls = cont_cls;
1551   /* FIXME: this memcpy can be up to 7% of our total runtime! */
1552   memcpy (&mq[1], msg, msg_size);
1553   mq->message_buf = (const char *) &mq[1];
1554   mq->message_buf_size = msg_size;
1555   mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1556   GNUNET_CONTAINER_DLL_insert_tail (n->messages_head, n->messages_tail, mq);
1557
1558   if ((GNUNET_SCHEDULER_NO_TASK == n->transmission_task) &&
1559       (NULL == n->is_active))
1560     n->transmission_task = GNUNET_SCHEDULER_add_now (&transmission_task, n);
1561 }
1562
1563
1564 /**
1565  * We have received a message from the given sender.  How long should
1566  * we delay before receiving more?  (Also used to keep the peer marked
1567  * as live).
1568  *
1569  * @param sender sender of the message
1570  * @param size size of the message
1571  * @param do_forward set to GNUNET_YES if the message should be forwarded to clients
1572  *                   GNUNET_NO if the neighbour is not connected or violates the quota,
1573  *                   GNUNET_SYSERR if the connection is not fully up yet
1574  * @return how long to wait before reading more from this sender
1575  */
1576 struct GNUNET_TIME_Relative
1577 GST_neighbours_calculate_receive_delay (const struct GNUNET_PeerIdentity
1578                                         *sender, ssize_t size, int *do_forward)
1579 {
1580   struct NeighbourMapEntry *n;
1581   struct GNUNET_TIME_Relative ret;
1582
1583   GNUNET_assert (neighbours != NULL);
1584
1585   n = lookup_neighbour (sender);
1586   if (n == NULL)
1587   {
1588     GST_neighbours_try_connect (sender);
1589     n = lookup_neighbour (sender);
1590     if (NULL == n)
1591     {
1592       GNUNET_STATISTICS_update (GST_stats,
1593                                 gettext_noop
1594                                 ("# messages discarded due to lack of neighbour record"),
1595                                 1, GNUNET_NO);
1596       *do_forward = GNUNET_NO;
1597       return GNUNET_TIME_UNIT_ZERO;
1598     }
1599   }
1600   if (!is_connected(n))
1601   {
1602     *do_forward = GNUNET_SYSERR;
1603     return GNUNET_TIME_UNIT_ZERO;
1604   }
1605   if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, size))
1606   {
1607     n->quota_violation_count++;
1608 #if DEBUG_TRANSPORT
1609     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1610                 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
1611                 n->in_tracker.available_bytes_per_s__,
1612                 n->quota_violation_count);
1613 #endif
1614     /* Discount 32k per violation */
1615     GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, -32 * 1024);
1616   }
1617   else
1618   {
1619     if (n->quota_violation_count > 0)
1620     {
1621       /* try to add 32k back */
1622       GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, 32 * 1024);
1623       n->quota_violation_count--;
1624     }
1625   }
1626   if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
1627   {
1628     GNUNET_STATISTICS_update (GST_stats,
1629                               gettext_noop
1630                               ("# bandwidth quota violations by other peers"),
1631                               1, GNUNET_NO);
1632     *do_forward = GNUNET_NO;
1633     return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
1634   }
1635   *do_forward = GNUNET_YES;
1636   ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 32 * 1024);
1637   if (ret.rel_value > 0)
1638   {
1639 #if DEBUG_TRANSPORT
1640     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1641                 "Throttling read (%llu bytes excess at %u b/s), waiting %llu ms before reading more.\n",
1642                 (unsigned long long) n->in_tracker.
1643                 consumption_since_last_update__,
1644                 (unsigned int) n->in_tracker.available_bytes_per_s__,
1645                 (unsigned long long) ret.rel_value);
1646 #endif
1647     GNUNET_STATISTICS_update (GST_stats,
1648                               gettext_noop ("# ms throttling suggested"),
1649                               (int64_t) ret.rel_value, GNUNET_NO);
1650   }
1651   return ret;
1652 }
1653
1654
1655 /**
1656  * Keep the connection to the given neighbour alive longer,
1657  * we received a KEEPALIVE (or equivalent).
1658  *
1659  * @param neighbour neighbour to keep alive
1660  */
1661 void
1662 GST_neighbours_keepalive (const struct GNUNET_PeerIdentity *neighbour)
1663 {
1664   struct NeighbourMapEntry *n;
1665
1666   GNUNET_assert (neighbours != NULL);
1667
1668   n = lookup_neighbour (neighbour);
1669   if (NULL == n)
1670   {
1671     GNUNET_STATISTICS_update (GST_stats,
1672                               gettext_noop
1673                               ("# KEEPALIVE messages discarded (not connected)"),
1674                               1, GNUNET_NO);
1675     return;
1676   }
1677   GNUNET_SCHEDULER_cancel (n->timeout_task);
1678   n->timeout_task =
1679       GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1680                                     &neighbour_timeout_task, n);
1681 }
1682
1683
1684 /**
1685  * Change the incoming quota for the given peer.
1686  *
1687  * @param neighbour identity of peer to change qutoa for
1688  * @param quota new quota
1689  */
1690 void
1691 GST_neighbours_set_incoming_quota (const struct GNUNET_PeerIdentity *neighbour,
1692                                    struct GNUNET_BANDWIDTH_Value32NBO quota)
1693 {
1694   struct NeighbourMapEntry *n;
1695
1696   GNUNET_assert (neighbours != NULL);
1697
1698   n = lookup_neighbour (neighbour);
1699   if (n == NULL)
1700   {
1701     GNUNET_STATISTICS_update (GST_stats,
1702                               gettext_noop
1703                               ("# SET QUOTA messages ignored (no such peer)"),
1704                               1, GNUNET_NO);
1705     return;
1706   }
1707   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker, quota);
1708   if (0 != ntohl (quota.value__))
1709     return;
1710 #if DEBUG_TRANSPORT
1711   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting peer `%4s' due to `%s'\n",
1712               GNUNET_i2s (&n->id), "SET_QUOTA");
1713 #endif
1714   if (is_connected(n))
1715     GNUNET_STATISTICS_update (GST_stats,
1716                               gettext_noop ("# disconnects due to quota of 0"), 1,
1717                               GNUNET_NO);
1718   disconnect_neighbour (n);
1719 }
1720
1721
1722 /**
1723  * Closure for the neighbours_iterate function.
1724  */
1725 struct IteratorContext
1726 {
1727   /**
1728    * Function to call on each connected neighbour.
1729    */
1730   GST_NeighbourIterator cb;
1731
1732   /**
1733    * Closure for 'cb'.
1734    */
1735   void *cb_cls;
1736 };
1737
1738
1739 /**
1740  * Call the callback from the closure for each connected neighbour.
1741  *
1742  * @param cls the 'struct IteratorContext'
1743  * @param key the hash of the public key of the neighbour
1744  * @param value the 'struct NeighbourMapEntry'
1745  * @return GNUNET_OK (continue to iterate)
1746  */
1747 static int
1748 neighbours_iterate (void *cls, const GNUNET_HashCode * key, void *value)
1749 {
1750   struct IteratorContext *ic = cls;
1751   struct NeighbourMapEntry *n = value;
1752
1753   if (!is_connected(n))
1754     return GNUNET_OK;
1755
1756   ic->cb (ic->cb_cls, &n->id, NULL, 0, n->plugin_name, n->addr, n->addrlen);
1757   return GNUNET_OK;
1758 }
1759
1760
1761 /**
1762  * Iterate over all connected neighbours.
1763  *
1764  * @param cb function to call
1765  * @param cb_cls closure for cb
1766  */
1767 void
1768 GST_neighbours_iterate (GST_NeighbourIterator cb, void *cb_cls)
1769 {
1770   struct IteratorContext ic;
1771
1772   GNUNET_assert (neighbours != NULL);
1773
1774   ic.cb = cb;
1775   ic.cb_cls = cb_cls;
1776   GNUNET_CONTAINER_multihashmap_iterate (neighbours, &neighbours_iterate, &ic);
1777 }
1778
1779 /**
1780  * If we have an active connection to the given target, it must be shutdown.
1781  *
1782  * @param target peer to disconnect from
1783  */
1784 void
1785 GST_neighbours_force_disconnect (const struct GNUNET_PeerIdentity *target)
1786 {
1787   struct NeighbourMapEntry *n;
1788
1789   GNUNET_assert (neighbours != NULL);
1790
1791   n = lookup_neighbour (target);
1792   if (NULL == n)
1793     return;                     /* not active */
1794   if (is_connected(n))
1795   {
1796     send_disconnect(&n->id, n->plugin_name, n->addr, n->addrlen, n->session);
1797
1798     n = lookup_neighbour (target);
1799     if (NULL == n)
1800       return;                     /* gone already */
1801   }
1802   disconnect_neighbour (n);
1803 }
1804
1805
1806 /**
1807  * We received a disconnect message from the given peer,
1808  * validate and process.
1809  * 
1810  * @param peer sender of the message
1811  * @param msg the disconnect message
1812  */
1813 void
1814 GST_neighbours_handle_disconnect_message (const struct GNUNET_PeerIdentity *peer,
1815                                           const struct GNUNET_MessageHeader *msg)
1816 {
1817   struct NeighbourMapEntry *n;
1818   const struct SessionDisconnectMessage *sdm;
1819   GNUNET_HashCode hc;
1820
1821 #if DEBUG_TRANSPORT
1822   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1823       "Received DISCONNECT message from peer `%s'\n", GNUNET_i2s (peer));
1824 #endif
1825
1826   if (ntohs (msg->size) != sizeof (struct SessionDisconnectMessage))
1827   {
1828     // GNUNET_break_op (0);
1829     GNUNET_STATISTICS_update (GST_stats,
1830                               gettext_noop ("# disconnect messages ignored (old format)"), 1,
1831                               GNUNET_NO);
1832     return;
1833   }
1834   sdm = (const struct SessionDisconnectMessage* ) msg;
1835   n = lookup_neighbour (peer);
1836   if (NULL == n)
1837     return;                     /* gone already */
1838   if (GNUNET_TIME_absolute_ntoh (sdm->timestamp).abs_value <=
1839       n->connect_ts.abs_value)
1840   {
1841     GNUNET_STATISTICS_update (GST_stats,
1842                               gettext_noop ("# disconnect messages ignored (timestamp)"), 1,
1843                               GNUNET_NO);
1844     return;
1845   }
1846   GNUNET_CRYPTO_hash (&sdm->public_key,
1847                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1848                       &hc);
1849   if (0 != memcmp (peer,
1850                    &hc,
1851                    sizeof (struct GNUNET_PeerIdentity)))
1852   {
1853     GNUNET_break_op (0);
1854     return;
1855   }
1856   if (ntohl (sdm->purpose.size) != 
1857       sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
1858       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
1859       sizeof (struct GNUNET_TIME_AbsoluteNBO))
1860   {
1861     GNUNET_break_op (0);
1862     return;
1863   }
1864   if (GNUNET_OK !=
1865       GNUNET_CRYPTO_rsa_verify (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT,
1866                                 &sdm->purpose,
1867                                 &sdm->signature,
1868                                 &sdm->public_key))
1869   {
1870     GNUNET_break_op (0);
1871     return;
1872   }
1873   GST_neighbours_force_disconnect (peer);
1874 }
1875
1876 /**
1877  * We received a 'SESSION_CONNECT_ACK' message from the other peer.
1878  * Consider switching to it.
1879  *
1880  * @param message possibly a 'struct SessionConnectMessage' (check format)
1881  * @param peer identity of the peer to switch the address for
1882  * @param plugin_name name of transport that delivered the PONG
1883  * @param address address of the other peer, NULL if other peer
1884  *                       connected to us
1885  * @param address_len number of bytes in address
1886  * @param session session to use (or NULL)
1887  * @param ats performance data
1888  * @param ats_count number of entries in ats
1889   */
1890 void
1891 GST_neighbours_handle_connect_ack (const struct GNUNET_MessageHeader *message,
1892                                const struct GNUNET_PeerIdentity *peer,
1893                                const char *plugin_name,
1894                                const char *sender_address, uint16_t sender_address_len,
1895                                struct Session *session,
1896                                const struct GNUNET_ATS_Information *ats,
1897                                uint32_t ats_count)
1898 {
1899   const struct SessionConnectMessage *scm;
1900   struct QuotaSetMessage q_msg;
1901   struct GNUNET_MessageHeader msg;
1902   struct NeighbourMapEntry *n;
1903   size_t msg_len;
1904   size_t ret;
1905   int was_connected;
1906
1907 #if DEBUG_TRANSPORT
1908   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1909       "Received CONNECT_ACK message from peer `%s'\n", GNUNET_i2s (peer));
1910 #endif
1911
1912   if (ntohs (message->size) != sizeof (struct SessionConnectMessage))
1913   {
1914     GNUNET_break_op (0);
1915     return;
1916   }
1917
1918   scm = (const struct SessionConnectMessage *) message;
1919   GNUNET_break_op (ntohl (scm->reserved) == 0);
1920   n = lookup_neighbour (peer);
1921   if (NULL == n)
1922     n = setup_neighbour (peer);
1923 /*
1924   if (n->state != S_CONNECT_SENT)
1925   {
1926     GNUNET_break (0);
1927     send_disconnect(&n->id, n->plugin_name, n->addr, n->addrlen, n->session);
1928     return;
1929   }
1930 */
1931   if (NULL != session)
1932     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1933                      "transport-ats",
1934                      "Giving ATS session %p of plugin %s for peer %s\n",
1935                      session,
1936                      plugin_name,
1937                      GNUNET_i2s (peer));
1938   GNUNET_ATS_address_update (GST_ats,
1939                              peer,
1940                              plugin_name, sender_address, sender_address_len,
1941                              session, ats, ats_count);
1942
1943   was_connected = is_connected(n);
1944   if (!is_connected(n))
1945     change_state (n, S_CONNECTED);
1946
1947 #if DEBUG_TRANSPORT
1948   GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1949               "Setting inbound quota of %u for peer `%s' to \n",
1950               ntohl (n->bandwidth_in.value__), GNUNET_i2s (&n->id));
1951 #endif
1952   GST_neighbours_set_incoming_quota(&n->id, n->bandwidth_in);
1953
1954   /* send ACK (ACK)*/
1955   msg_len =  sizeof (msg);
1956   msg.size = htons (msg_len);
1957   msg.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_ACK);
1958
1959   ret = send_with_plugin (&n->id, (const char *) &msg, msg_len, UINT32_MAX,
1960                           GNUNET_TIME_UNIT_FOREVER_REL,
1961                           n->session, n->plugin_name, n->addr, n->addrlen,
1962                           GNUNET_YES, NULL, NULL);
1963
1964   if (ret == GNUNET_SYSERR)
1965     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1966               "Failed to send SESSION_ACK to `%4s' using plugin `%s' address '%s' session %X\n",
1967               GNUNET_i2s (&n->id), n->plugin_name,
1968               (n->addrlen == 0) ? "<inbound>" : GST_plugins_a2s (n->plugin_name,
1969                                                                  n->addr,
1970                                                                  n->addrlen),
1971               n->session);
1972
1973
1974   if (!was_connected)
1975   {
1976     if (n->keepalive_task == GNUNET_SCHEDULER_NO_TASK)
1977       n->keepalive_task = GNUNET_SCHEDULER_add_delayed (KEEPALIVE_FREQUENCY,
1978                                                         &neighbour_keepalive_task,
1979                                                         n);
1980
1981     neighbours_connected++;
1982     GNUNET_STATISTICS_update (GST_stats, gettext_noop ("# peers connected"), 1,
1983                               GNUNET_NO);
1984 #if DEBUG_TRANSPORT
1985     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1986               "Notify about connect of `%4s' using plugin `%s' address '%s' session %X LINE %u\n",
1987               GNUNET_i2s (&n->id), n->plugin_name,
1988               (n->addrlen == 0) ? "<inbound>" : GST_plugins_a2s (n->plugin_name,
1989                                                                  n->addr,
1990                                                                  n->addrlen),
1991               n->session, __LINE__);
1992 #endif
1993     connect_notify_cb (callback_cls, &n->id, ats, ats_count);
1994   }
1995
1996 #if DEBUG_TRANSPORT
1997     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1998                 "Sending outbound quota of %u Bps for peer `%s' to all clients\n",
1999                 ntohl (n->bandwidth_out.value__), GNUNET_i2s (peer));
2000 #endif
2001     q_msg.header.size = htons (sizeof (struct QuotaSetMessage));
2002     q_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA);
2003     q_msg.quota = n->bandwidth_out;
2004     q_msg.peer = (*peer);
2005     GST_clients_broadcast (&q_msg.header, GNUNET_NO);
2006
2007 }
2008
2009 void
2010 GST_neighbours_handle_ack (const struct GNUNET_MessageHeader *message,
2011     const struct GNUNET_PeerIdentity *peer,
2012     const char *plugin_name,
2013     const char *sender_address, uint16_t sender_address_len,
2014     struct Session *session,
2015     const struct GNUNET_ATS_Information *ats,
2016     uint32_t ats_count)
2017 {
2018   struct NeighbourMapEntry *n;
2019   struct QuotaSetMessage q_msg;
2020   int was_connected;
2021
2022 #if DEBUG_TRANSPORT
2023   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2024       "Received ACK message from peer `%s'\n", GNUNET_i2s (peer));
2025 #endif
2026
2027   if (ntohs (message->size) != sizeof (struct GNUNET_MessageHeader))
2028   {
2029     GNUNET_break_op (0);
2030     return;
2031   }
2032
2033   n = lookup_neighbour (peer);
2034   if (NULL == n)
2035   {
2036     send_disconnect(peer, plugin_name, sender_address, sender_address_len, session);
2037     GNUNET_break (0);
2038     return;
2039   }
2040
2041   if (is_connected(n))
2042     return;
2043
2044   if (NULL != session)
2045     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2046                      "transport-ats",
2047                      "Giving ATS session %p of plugin %s for peer %s\n",
2048                      session,
2049                      plugin_name,
2050                      GNUNET_i2s (peer));
2051   GNUNET_ATS_address_update (GST_ats,
2052                              peer,
2053                              plugin_name, sender_address, sender_address_len,
2054                              session, ats, ats_count);
2055
2056   was_connected = is_connected(n);
2057   change_state (n, S_CONNECTED);
2058
2059   GST_neighbours_set_incoming_quota(&n->id, n->bandwidth_in);
2060
2061   if (n->keepalive_task == GNUNET_SCHEDULER_NO_TASK)
2062     n->keepalive_task = GNUNET_SCHEDULER_add_delayed (KEEPALIVE_FREQUENCY,
2063                                                       &neighbour_keepalive_task,
2064                                                       n);
2065
2066   if (!was_connected)
2067   {
2068   neighbours_connected++;
2069   GNUNET_STATISTICS_update (GST_stats, gettext_noop ("# peers connected"), 1,
2070                             GNUNET_NO);
2071
2072 #if DEBUG_TRANSPORT
2073     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2074               "Notify about connect of `%4s' using plugin `%s' address '%s' session %X LINE %u\n",
2075               GNUNET_i2s (&n->id), n->plugin_name,
2076               (n->addrlen == 0) ? "<inbound>" : GST_plugins_a2s (n->plugin_name,
2077                                                                  n->addr,
2078                                                                  n->addrlen),
2079               n->session, __LINE__);
2080 #endif
2081   connect_notify_cb (callback_cls, &n->id, ats, ats_count);
2082   }
2083 #if DEBUG_TRANSPORT
2084   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2085               "Sending outbound quota of %u Bps for peer `%s' to all clients\n",
2086               ntohl (n->bandwidth_out.value__), GNUNET_i2s (peer));
2087 #endif
2088
2089   q_msg.header.size = htons (sizeof (struct QuotaSetMessage));
2090   q_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA);
2091   q_msg.quota = n->bandwidth_out;
2092   q_msg.peer = (*peer);
2093   GST_clients_broadcast (&q_msg.header, GNUNET_NO);
2094
2095 }
2096
2097 struct BlackListCheckContext
2098 {
2099   struct GNUNET_ATS_Information *ats;
2100
2101   uint32_t ats_count;
2102
2103   struct Session *session;
2104
2105   char *sender_address;
2106
2107   uint16_t sender_address_len;
2108
2109   char *plugin_name;
2110
2111   struct GNUNET_TIME_Absolute ts;
2112 };
2113
2114
2115 static void
2116 handle_connect_blacklist_cont (void *cls,
2117                                const struct GNUNET_PeerIdentity
2118                                * peer, int result)
2119 {
2120   struct NeighbourMapEntry *n;
2121   struct BlackListCheckContext * bcc = cls;
2122
2123 #if DEBUG_TRANSPORT
2124   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2125       "Blacklist check due to CONNECT message: `%s'\n", GNUNET_i2s (peer), (result == GNUNET_OK) ? "ALLOWED" : "FORBIDDEN");
2126 #endif
2127
2128   /* not allowed */
2129   if (GNUNET_OK != result)
2130   {
2131     GNUNET_free (bcc);
2132     return;
2133   }
2134
2135   n = lookup_neighbour (peer);
2136   if (NULL == n)
2137     n = setup_neighbour (peer);
2138
2139   if (bcc->ts.abs_value > n->connect_ts.abs_value)
2140   {
2141     if (NULL != bcc->session)
2142       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
2143                        "transport-ats",
2144                        "Giving ATS session %p of plugin %s address `%s' for peer %s\n",
2145                        bcc->session,
2146                        bcc->plugin_name,
2147                        GST_plugins_a2s (bcc->plugin_name, bcc->sender_address, bcc->sender_address_len),
2148                        GNUNET_i2s (peer));
2149     GNUNET_ATS_address_update (GST_ats,
2150                                peer,
2151                                bcc->plugin_name, bcc->sender_address, bcc->sender_address_len,
2152                                bcc->session, bcc->ats, bcc->ats_count);
2153     n->connect_ts = bcc->ts;
2154   }
2155
2156   GNUNET_free (bcc);
2157 /*
2158   if (n->state != S_NOT_CONNECTED)
2159     return;*/
2160   change_state (n, S_CONNECT_RECV);
2161
2162   /* Ask ATS for an address to connect via that address */
2163   if (n->ats_suggest != GNUNET_SCHEDULER_NO_TASK)
2164     GNUNET_SCHEDULER_cancel(n->ats_suggest);
2165   n->ats_suggest = GNUNET_SCHEDULER_add_delayed (ATS_RESPONSE_TIMEOUT, ats_suggest_cancel, n);
2166   GNUNET_ATS_suggest_address(GST_ats, peer);
2167 }
2168
2169 /**
2170  * We received a 'SESSION_CONNECT' message from the other peer.
2171  * Consider switching to it.
2172  *
2173  * @param message possibly a 'struct SessionConnectMessage' (check format)
2174  * @param peer identity of the peer to switch the address for
2175  * @param plugin_name name of transport that delivered the PONG
2176  * @param address address of the other peer, NULL if other peer
2177  *                       connected to us
2178  * @param address_len number of bytes in address
2179  * @param session session to use (or NULL)
2180  * @param ats performance data
2181  * @param ats_count number of entries in ats (excluding 0-termination)
2182   */
2183 void
2184 GST_neighbours_handle_connect (const struct GNUNET_MessageHeader *message,
2185                                const struct GNUNET_PeerIdentity *peer,
2186                                const char *plugin_name,
2187                                const char *sender_address, uint16_t sender_address_len,
2188                                struct Session *session,
2189                                const struct GNUNET_ATS_Information *ats,
2190                                uint32_t ats_count)
2191 {
2192   const struct SessionConnectMessage *scm;
2193   struct NeighbourMapEntry * n;
2194   struct BlackListCheckContext * bcc = NULL;
2195
2196 #if DEBUG_TRANSPORT
2197   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2198       "Received CONNECT message from peer `%s'\n", GNUNET_i2s (peer));
2199 #endif
2200
2201   if (ntohs (message->size) != sizeof (struct SessionConnectMessage))
2202   {
2203     GNUNET_break_op (0);
2204     return;
2205   }
2206
2207   scm = (const struct SessionConnectMessage *) message;
2208   GNUNET_break_op (ntohl (scm->reserved) == 0);
2209
2210   n = lookup_neighbour(peer);
2211   if (n != NULL)
2212   {
2213     /* connected peer switches addresses */
2214     if (is_connected(n))
2215     {
2216       GNUNET_ATS_address_update(GST_ats, peer, plugin_name, sender_address, sender_address_len, session, ats, ats_count);
2217       return;
2218     }
2219   }
2220
2221   /* we are not connected to this peer */
2222   /* do blacklist check*/
2223   bcc = GNUNET_malloc (sizeof (struct BlackListCheckContext) +
2224             sizeof (struct GNUNET_ATS_Information) * ats_count +
2225             sender_address_len +
2226             strlen (plugin_name)+1);
2227
2228   bcc->ts = GNUNET_TIME_absolute_ntoh (scm->timestamp);
2229
2230   bcc->ats_count = ats_count;
2231   bcc->sender_address_len = sender_address_len;
2232   bcc->session = session;
2233
2234   bcc->ats = (struct GNUNET_ATS_Information *) &bcc[1];
2235   memcpy (bcc->ats, ats,sizeof (struct GNUNET_ATS_Information) * ats_count );
2236
2237   bcc->sender_address = (char *) &bcc->ats[ats_count];
2238   memcpy (bcc->sender_address, sender_address , sender_address_len);
2239
2240   bcc->plugin_name = &bcc->sender_address[sender_address_len];
2241   strcpy (bcc->plugin_name, plugin_name);
2242
2243   GST_blacklist_test_allowed (peer, plugin_name, handle_connect_blacklist_cont, bcc);
2244 }
2245
2246
2247 /* end of file gnunet-service-transport_neighbours.c */