1c7cc9f59df09e4907966bb6586fc68248d0779a
[oweals/gnunet.git] / src / transport / gnunet-service-transport_neighbours.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010,2011,2012 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  * TODO:
27  * - "address_change_cb" is NEVER invoked; when should we call this one exactly?
28  * - TEST, TEST, TEST...
29  */
30 #include "platform.h"
31 #include "gnunet_ats_service.h"
32 #include "gnunet-service-transport_neighbours.h"
33 #include "gnunet-service-transport_plugins.h"
34 #include "gnunet-service-transport_validation.h"
35 #include "gnunet-service-transport_clients.h"
36 #include "gnunet-service-transport.h"
37 #include "gnunet_peerinfo_service.h"
38 #include "gnunet-service-transport_blacklist.h"
39 #include "gnunet_constants.h"
40 #include "transport.h"
41
42
43 /**
44  * Size of the neighbour hash map.
45  */
46 #define NEIGHBOUR_TABLE_SIZE 256
47
48 /**
49  * Time we give plugin to transmit DISCONNECT message before the
50  * neighbour entry self-destructs.
51  */
52 #define DISCONNECT_SENT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100)
53
54 /**
55  * How often must a peer violate bandwidth quotas before we start
56  * to simply drop its messages?
57  */
58 #define QUOTA_VIOLATION_DROP_THRESHOLD 10
59
60 /**
61  * How often do we send KEEPALIVE messages to each of our neighbours and measure
62  * the latency with this neighbour?
63  * (idle timeout is 5 minutes or 300 seconds, so with 100s interval we
64  * send 3 keepalives in each interval, so 3 messages would need to be
65  * lost in a row for a disconnect).
66  */
67 #define KEEPALIVE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 100)
68
69 /**
70  * How long are we willing to wait for a response from ATS before timing out?
71  */
72 #define ATS_RESPONSE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 500)
73
74 /**
75  * How long are we willing to wait for an ACK from the other peer before
76  * giving up on our connect operation?
77  */
78 #define SETUP_CONNECTION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
79
80 /**
81  * How long are we willing to wait for a successful reconnect if 
82  * an existing connection went down?  Much shorter than the
83  * usual SETUP_CONNECTION_TIMEOUT as we do not inform the
84  * higher layers about the disconnect during this period.
85  */
86 #define FAST_RECONNECT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
87
88 /**
89  * How long are we willing to wait for a response from the blacklist
90  * subsystem before timing out?
91  */
92 #define BLACKLIST_RESPONSE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 500)
93
94
95 GNUNET_NETWORK_STRUCT_BEGIN
96
97 /**
98  * Message a peer sends to another to indicate that it intends to
99  * setup a connection/session for data exchange.  A 'SESSION_CONNECT'
100  * should be answered with a 'SESSION_CONNECT_ACK' with the same body
101  * to confirm.  A 'SESSION_CONNECT_ACK' should then be followed with
102  * a 'SESSION_ACK'.  Once the 'SESSION_ACK' is received, both peers 
103  * should be connected.
104  */
105 struct SessionConnectMessage
106 {
107   /**
108    * Header of type 'GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT'
109    * or 'GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT_ACK'
110    */
111   struct GNUNET_MessageHeader header;
112
113   /**
114    * Always zero.
115    */
116   uint32_t reserved GNUNET_PACKED;
117
118   /**
119    * Absolute time at the sender.  Only the most recent connect
120    * message implies which session is preferred by the sender.
121    */
122   struct GNUNET_TIME_AbsoluteNBO timestamp;
123
124 };
125
126
127 /**
128  * Message we send to the other peer to notify him that we intentionally
129  * are disconnecting (to reduce timeouts).  This is just a friendly 
130  * notification, peers must not rely on always receiving disconnect
131  * messages.
132  */
133 struct SessionDisconnectMessage
134 {
135   /**
136    * Header of type 'GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT'
137    */
138   struct GNUNET_MessageHeader header;
139
140   /**
141    * Always zero.
142    */
143   uint32_t reserved GNUNET_PACKED;
144
145   /**
146    * Purpose of the signature.  Extends over the timestamp.
147    * Purpose should be GNUNET_SIGNATURE_PURPOSE_TRANSPORT_DISCONNECT.
148    */
149   struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
150
151   /**
152    * Absolute time at the sender.  Only the most recent connect
153    * message implies which session is preferred by the sender.
154    */
155   struct GNUNET_TIME_AbsoluteNBO timestamp;
156
157   /**
158    * Public key of the sender.
159    */
160   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded public_key;
161
162   /**
163    * Signature of the peer that sends us the disconnect.  Only
164    * valid if the timestamp is AFTER the timestamp from the
165    * corresponding 'CONNECT' message.
166    */
167   struct GNUNET_CRYPTO_RsaSignature signature;
168
169 };
170
171 GNUNET_NETWORK_STRUCT_END
172
173
174 /**
175  * For each neighbour we keep a list of messages
176  * that we still want to transmit to the neighbour.
177  */
178 struct MessageQueue
179 {
180
181   /**
182    * This is a doubly linked list.
183    */
184   struct MessageQueue *next;
185
186   /**
187    * This is a doubly linked list.
188    */
189   struct MessageQueue *prev;
190
191   /**
192    * Function to call once we're done.
193    */
194   GST_NeighbourSendContinuation cont;
195
196   /**
197    * Closure for 'cont'
198    */
199   void *cont_cls;
200
201   /**
202    * The message(s) we want to transmit, GNUNET_MessageHeader(s)
203    * stuck together in memory.  Allocated at the end of this struct.
204    */
205   const char *message_buf;
206
207   /**
208    * Size of the message buf
209    */
210   size_t message_buf_size;
211
212   /**
213    * At what time should we fail?
214    */
215   struct GNUNET_TIME_Absolute timeout;
216
217 };
218
219
220 /**
221  * Possible state of a neighbour.  Initially, we are S_NOT_CONNECTED.
222  *
223  * Then, there are two main paths. If we receive a CONNECT message, we
224  * first run a check against the blacklist and ask ATS for a
225  * suggestion.  (S_CONNECT_RECV_ATS).  If the blacklist comes back
226  * positive, we give the address to ATS.  If ATS makes a suggestion,
227  * we ALSO give that suggestion to the blacklist
228  * (S_CONNECT_RECV_BLACKLIST).  Once the blacklist approves the
229  * address we got from ATS, we send our CONNECT_ACK and go to
230  * S_CONNECT_RECV_ACK.  If we receive a SESSION_ACK, we go to
231  * S_CONNECTED (and notify everyone about the new connection).  If the
232  * operation times out, we go to S_DISCONNECT.
233  *
234  * The other case is where we transmit a CONNECT message first.  We
235  * start with S_INIT_ATS.  If we get an address, we enter
236  * S_INIT_BLACKLIST and check the blacklist.  If the blacklist is OK
237  * with the connection, we actually send the CONNECT message and go to
238  * state S_CONNECT_SENT.  Once we receive a CONNECT_ACK, we go to
239  * S_CONNECTED (and notify everyone about the new connection and send
240  * back a SESSION_ACK).  If the operation times out, we go to
241  * S_DISCONNECT.
242  *
243  * If the session is in trouble (i.e. transport-level disconnect or
244  * timeout), we go to S_RECONNECT_ATS where we ask ATS for a new
245  * address (we don't notify anyone about the disconnect yet).  Once we
246  * have a new address, we go to S_RECONNECT_BLACKLIST to check the new
247  * address against the blacklist.  If the blacklist approves, we enter
248  * S_RECONNECT_SENT and send a CONNECT message.  If we receive a
249  * CONNECT_ACK, we go to S_CONNECTED and nobody noticed that we had
250  * trouble; we also send a SESSION_ACK at this time just in case.  If
251  * the operation times out, we go to S_DISCONNECT (and notify everyone
252  * about the lost connection).
253  *
254  * If ATS decides to switch addresses while we have a normal
255  * connection, we go to S_CONNECTED_SWITCHING_BLACKLIST to check the
256  * new address against the blacklist.  If the blacklist approves, we
257  * go to S_CONNECTED_SWITCHING_CONNECT_SENT and send a
258  * SESSION_CONNECT.  If we get a SESSION_ACK back, we switch the
259  * primary connection to the suggested alternative from ATS, go back
260  * to S_CONNECTED and send a SESSION_ACK to the other peer just to be
261  * sure.  If the operation times out (or the blacklist disapproves),
262  * we go to S_CONNECTED (and notify ATS that the given alternative
263  * address is "invalid").
264  *
265  * Once a session is in S_DISCONNECT, it is cleaned up and then goes
266  * to (S_DISCONNECT_FINISHED).  If we receive an explicit disconnect
267  * request, we can go from any state to S_DISCONNECT, possibly after
268  * generating disconnect notifications.
269  *
270  * Note that it is quite possible that while we are in any of these
271  * states, we could receive a 'CONNECT' request from the other peer.
272  * We then enter a 'weird' state where we pursue our own primary state
273  * machine (as described above), but with the 'send_connect_ack' flag
274  * set to 1.  If our state machine allows us to send a 'CONNECT_ACK'
275  * (because we have an acceptable address), we send the 'CONNECT_ACK'
276  * and set the 'send_connect_ack' to 2.  If we then receive a
277  * 'SESSION_ACK', we go to 'S_CONNECTED' (and reset 'send_connect_ack'
278  * to 0).
279  * 
280  */ 
281 enum State
282 {
283   /**
284    * fresh peer or completely disconnected
285    */
286   S_NOT_CONNECTED = 0,
287
288   /**
289    * Asked to initiate connection, trying to get address from ATS
290    */
291   S_INIT_ATS,
292
293   /**
294    * Asked to initiate connection, trying to get address approved
295    * by blacklist.
296    */
297   S_INIT_BLACKLIST,
298
299   /**
300    * Sent CONNECT message to other peer, waiting for CONNECT_ACK
301    */
302   S_CONNECT_SENT,
303
304   /**
305    * Received a CONNECT, asking ATS about address suggestions.
306    */
307   S_CONNECT_RECV_ATS,
308
309   /**
310    * Received CONNECT from other peer, got an address, checking with blacklist.
311    */
312   S_CONNECT_RECV_BLACKLIST,
313
314   /**
315    * CONNECT request from other peer was SESSION_ACK'ed, waiting for
316    * SESSION_ACK.
317    */
318   S_CONNECT_RECV_ACK,
319
320   /**
321    * Got our CONNECT_ACK/SESSION_ACK, connection is up.
322    */
323   S_CONNECTED,
324
325   /**
326    * Connection got into trouble, rest of the system still believes
327    * it to be up, but we're getting a new address from ATS.
328    */
329   S_RECONNECT_ATS,
330
331   /**
332    * Connection got into trouble, rest of the system still believes
333    * it to be up; we are checking the new address against the blacklist.
334    */
335   S_RECONNECT_BLACKLIST,
336
337   /**
338    * Sent CONNECT over new address (either by ATS telling us to switch
339    * addresses or from RECONNECT_ATS); if this fails, we need to tell
340    * the rest of the system about a disconnect.
341    */
342   S_RECONNECT_SENT,
343
344   /**
345    * We have some primary connection, but ATS suggested we switch
346    * to some alternative; we're now checking the alternative against
347    * the blacklist.
348    */
349   S_CONNECTED_SWITCHING_BLACKLIST,
350
351   /** 
352    * We have some primary connection, but ATS suggested we switch
353    * to some alternative; we now sent a CONNECT message for the
354    * alternative session to the other peer and waiting for a
355    * CONNECT_ACK to make this our primary connection.
356    */
357   S_CONNECTED_SWITCHING_CONNECT_SENT,
358
359   /**
360    * Disconnect in progress (we're sending the DISCONNECT message to the
361    * other peer; after that is finished, the state will be cleaned up).
362    */
363   S_DISCONNECT,
364
365   /**
366    * We're finished with the disconnect; clean up state now!
367    */
368   S_DISCONNECT_FINISHED
369 };
370
371
372 /**
373  * A possible address we could use to communicate with a neighbour.
374  */
375 struct NeighbourAddress
376 {
377
378   /**
379    * Active session for this address.
380    */
381   struct Session *session;
382
383   /**
384    * Network-level address information.
385    */
386   struct GNUNET_HELLO_Address *address;
387
388   /**
389    * Timestamp of the 'SESSION_CONNECT' message we sent to the other
390    * peer for this address.  Use to check that the ACK is in response
391    * to our most recent 'CONNECT'.
392    */
393   struct GNUNET_TIME_Absolute connect_timestamp;
394
395   /**
396    * Inbound bandwidth from ATS for this address.
397    */
398   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in;
399
400   /**
401    * Outbound bandwidth from ATS for this address.
402    */
403   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out;
404
405   /**
406    * Did we tell ATS that this is our 'active' address?
407    */
408   int ats_active;
409   
410 };
411
412
413 /**
414  * Entry in neighbours.
415  */
416 struct NeighbourMapEntry
417 {
418
419   /**
420    * Head of list of messages we would like to send to this peer;
421    * must contain at most one message per client.
422    */
423   struct MessageQueue *messages_head;
424
425   /**
426    * Tail of list of messages we would like to send to this peer; must
427    * contain at most one message per client.
428    */
429   struct MessageQueue *messages_tail;
430
431   /**
432    * Are we currently trying to send a message? If so, which one?
433    */
434   struct MessageQueue *is_active;
435
436   /**
437    * Primary address we currently use to communicate with the neighbour.
438    */
439   struct NeighbourAddress primary_address;
440
441   /**
442    * Alternative address currently under consideration for communicating
443    * with the neighbour.
444    */
445   struct NeighbourAddress alternative_address;
446
447   /**
448    * Identity of this neighbour.
449    */
450   struct GNUNET_PeerIdentity id;
451
452   /**
453    * Main task that drives this peer (timeouts, keepalives, etc.).
454    * Always runs the 'master_task'.
455    */
456   GNUNET_SCHEDULER_TaskIdentifier task;
457
458   /**
459    * At what time should we sent the next keep-alive message?
460    */
461   struct GNUNET_TIME_Absolute keep_alive_time;
462
463   /**
464    * At what time did we sent the last keep-alive message?  Used 
465    * to calculate round-trip time ("latency").
466    */
467   struct GNUNET_TIME_Absolute last_keep_alive_time;
468
469   /**
470    * Timestamp we should include in our next CONNECT_ACK message.
471    * (only valid if 'send_connect_ack' is GNUNET_YES).  Used to build
472    * our CONNECT_ACK message.
473    */
474   struct GNUNET_TIME_Absolute connect_ack_timestamp;
475
476   /**
477    * Time where we should cut the connection (timeout) if we don't
478    * make progress in the state machine (or get a KEEPALIVE_RESPONSE
479    * if we are in S_CONNECTED).
480    */
481   struct GNUNET_TIME_Absolute timeout;
482
483   /**
484    * Latest calculated latency value
485    */
486   struct GNUNET_TIME_Relative latency;
487
488   /**
489    * Tracker for inbound bandwidth.
490    */
491   struct GNUNET_BANDWIDTH_Tracker in_tracker;
492
493   /**
494    * How often has the other peer (recently) violated the inbound
495    * traffic limit?  Incremented by 10 per violation, decremented by 1
496    * per non-violation (for each time interval).
497    */
498   unsigned int quota_violation_count;
499
500   /**
501    * The current state of the peer.
502    */
503   enum State state;
504
505   /**
506    * Did we sent an KEEP_ALIVE message and are we expecting a response?
507    */
508   int expect_latency_response;
509
510   /**
511    * Flag to set if we still need to send a CONNECT_ACK message to the other peer
512    * (once we have an address to use and the peer has been allowed by our
513    * blacklist).  Set to 1 if we need to send a CONNECT_ACK.  Set to 2 if we
514    * did send a CONNECT_ACK and should go to 'S_CONNECTED' upon receiving
515    * a 'SESSION_ACK' (regardless of what our own state machine might say).
516    */
517   int send_connect_ack;
518
519 };
520
521
522 /**
523  * Context for blacklist checks and the 'handle_test_blacklist_cont'
524  * function.  Stores information about ongoing blacklist checks.
525  */
526 struct BlackListCheckContext
527 {
528   
529   /**
530    * We keep blacklist checks in a DLL.
531    */
532   struct BlackListCheckContext *next;
533
534   /**
535    * We keep blacklist checks in a DLL.
536    */
537   struct BlackListCheckContext *prev;
538
539   /**
540    * Address that is being checked.
541    */
542   struct NeighbourAddress na;
543   
544   /**
545    * ATS information about the address.
546    */
547   struct GNUNET_ATS_Information *ats;
548
549   /**
550    * Handle to the ongoing blacklist check.
551    */
552   struct GST_BlacklistCheck *bc;
553
554   /**
555    * Size of the 'ats' array.
556    */
557   uint32_t ats_count;
558
559 };
560
561
562 /**
563  * Hash map from peer identities to the respective 'struct NeighbourMapEntry'.
564  */
565 static struct GNUNET_CONTAINER_MultiHashMap *neighbours;
566
567 /**
568  * We keep blacklist checks in a DLL so that we can find
569  * the 'sessions' in their 'struct NeighbourAddress' if
570  * a session goes down.
571  */
572 static struct BlackListCheckContext *bc_head;
573
574 /**
575  * We keep blacklist checks in a DLL.
576  */
577 static struct BlackListCheckContext *bc_tail;
578
579 /**
580  * Closure for connect_notify_cb, disconnect_notify_cb and address_change_cb
581  */
582 static void *callback_cls;
583
584 /**
585  * Function to call when we connected to a neighbour.
586  */
587 static GNUNET_TRANSPORT_NotifyConnect connect_notify_cb;
588
589 /**
590  * Function to call when we disconnected from a neighbour.
591  */
592 static GNUNET_TRANSPORT_NotifyDisconnect disconnect_notify_cb;
593
594 /**
595  * Function to call when we changed an active address of a neighbour.
596  */
597 static GNUNET_TRANSPORT_PeerIterateCallback address_change_cb;
598
599 /**
600  * counter for connected neighbours
601  */
602 static unsigned int neighbours_connected;
603
604 /**
605  * Number of bytes we have currently queued for transmission.
606  */
607 static unsigned long long bytes_in_send_queue;
608
609
610 /**
611  * Lookup a neighbour entry in the neighbours hash map.
612  *
613  * @param pid identity of the peer to look up
614  * @return the entry, NULL if there is no existing record
615  */
616 static struct NeighbourMapEntry *
617 lookup_neighbour (const struct GNUNET_PeerIdentity *pid)
618 {
619   if (NULL == neighbours)
620     return NULL;
621   return GNUNET_CONTAINER_multihashmap_get (neighbours, &pid->hashPubKey);
622 }
623
624 static const char *
625 print_state (int state)
626 {
627
628   switch (state)
629   {
630   case S_NOT_CONNECTED:
631     return "S_NOT_CONNECTED";
632     break;
633   case S_INIT_ATS:
634     return "S_INIT_ATS";
635     break;
636   case S_INIT_BLACKLIST:
637     return "S_INIT_BLACKLIST";
638     break;
639   case S_CONNECT_SENT:
640     return "S_CONNECT_SENT";
641     break;
642   case S_CONNECT_RECV_ATS:
643     return "S_CONNECT_RECV_ATS";
644     break;
645   case S_CONNECT_RECV_BLACKLIST:
646     return "S_CONNECT_RECV_BLACKLIST";
647     break;
648   case S_CONNECT_RECV_ACK:
649     return "S_CONNECT_RECV_ACK";
650     break;
651   case S_CONNECTED:
652     return "S_CONNECTED";
653     break;
654   case S_RECONNECT_ATS:
655     return "S_RECONNECT_ATS";
656     break;
657   case S_RECONNECT_BLACKLIST:
658     return "S_RECONNECT_BLACKLIST";
659     break;
660   case S_RECONNECT_SENT:
661     return "S_RECONNECT_SENT";
662     break;
663   case S_CONNECTED_SWITCHING_BLACKLIST:
664     return "S_CONNECTED_SWITCHING_BLACKLIST";
665     break;
666   case S_CONNECTED_SWITCHING_CONNECT_SENT:
667     return "S_CONNECTED_SWITCHING_CONNECT_SENT";
668     break;
669   case S_DISCONNECT:
670     return "S_DISCONNECT";
671     break;
672   case S_DISCONNECT_FINISHED:
673     return "S_DISCONNECT_FINISHED";
674     break;
675   default:
676     return "UNDEFINED";
677     GNUNET_break (0);
678     break;
679   }
680   GNUNET_break (0);
681   return "UNDEFINED";
682 }
683
684 /**
685  * Test if we're connected to the given peer.
686  *
687  * @param n neighbour entry of peer to test
688  * @return GNUNET_YES if we are connected, GNUNET_NO if not
689  */
690 static int
691 test_connected (struct NeighbourMapEntry *n)
692 {
693   if (NULL == n)
694     return GNUNET_NO;
695   switch (n->state)
696   {
697   case S_NOT_CONNECTED:
698   case S_INIT_ATS:
699   case S_INIT_BLACKLIST:
700   case S_CONNECT_SENT:
701   case S_CONNECT_RECV_ATS:
702   case S_CONNECT_RECV_BLACKLIST:
703   case S_CONNECT_RECV_ACK:
704     return GNUNET_NO;
705   case S_CONNECTED:
706   case S_RECONNECT_ATS:
707   case S_RECONNECT_BLACKLIST:
708   case S_RECONNECT_SENT:
709   case S_CONNECTED_SWITCHING_BLACKLIST:
710   case S_CONNECTED_SWITCHING_CONNECT_SENT:
711     return GNUNET_YES;
712   case S_DISCONNECT:
713   case S_DISCONNECT_FINISHED:
714     return GNUNET_NO;
715   default:
716     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
717     GNUNET_break (0);
718     break;
719   }
720   return GNUNET_SYSERR;
721 }
722
723 /**
724  * Send information about a new outbound quota to our clients.
725  *
726  * @param target affected peer
727  * @param quota new quota
728  */
729 static void
730 send_outbound_quota (const struct GNUNET_PeerIdentity *target,
731                      struct GNUNET_BANDWIDTH_Value32NBO quota)
732 {
733   struct QuotaSetMessage q_msg;
734
735   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
736               "Sending outbound quota of %u Bps for peer `%s' to all clients\n",
737               ntohl (quota.value__), GNUNET_i2s (target));
738   q_msg.header.size = htons (sizeof (struct QuotaSetMessage));
739   q_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA);
740   q_msg.quota = quota;
741   q_msg.peer = (*target);
742   GST_clients_broadcast (&q_msg.header, GNUNET_NO);
743 }
744
745
746 /**
747  * We don't need a given neighbour address any more.
748  * Release its resources and give appropriate notifications
749  * to ATS and other subsystems.
750  *
751  * @param na address we are done with; 'na' itself must NOT be 'free'd, only the contents!
752  */
753 static void
754 free_address (struct NeighbourAddress *na)
755 {
756   if (GNUNET_YES == na->ats_active)
757   {
758     GST_validation_set_address_use (na->address, na->session, GNUNET_NO, __LINE__);
759     GNUNET_ATS_address_in_use (GST_ats, na->address, na->session, GNUNET_NO);
760   }
761   na->ats_active = GNUNET_NO;
762   if (NULL != na->address)
763   {
764     GNUNET_HELLO_address_free (na->address);
765     na->address = NULL;
766   }
767   na->session = NULL;
768 }
769
770
771 /**
772  * Initialize the 'struct NeighbourAddress'.
773  *
774  * @param na neighbour address to initialize
775  * @param address address of the other peer, NULL if other peer
776  *                       connected to us
777  * @param session session to use (or NULL, in which case an
778  *        address must be setup)
779  * @param bandwidth_in inbound quota to be used when connection is up
780  * @param bandwidth_out outbound quota to be used when connection is up
781  * @param is_active GNUNET_YES to mark this as the active address with ATS
782  */
783 static void
784 set_address (struct NeighbourAddress *na,
785              const struct GNUNET_HELLO_Address *address,
786              struct Session *session,
787              struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
788              struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
789              int is_active)
790 {
791   struct GNUNET_TRANSPORT_PluginFunctions *papi;
792
793   if (NULL == (papi = GST_plugins_find (address->transport_name)))  
794   {
795     GNUNET_break (0);
796     return;
797   }
798   if (session == na->session)
799   {
800     na->bandwidth_in = bandwidth_in;
801     na->bandwidth_out = bandwidth_out;
802     if (is_active != na->ats_active)
803     {
804       na->ats_active = is_active;
805       GNUNET_ATS_address_in_use (GST_ats, na->address, na->session, is_active);
806       GST_validation_set_address_use (na->address, na->session, is_active,  __LINE__);
807     }
808     if (GNUNET_YES == is_active)
809     {
810       /* FIXME: is this the right place to set quotas? */
811       GST_neighbours_set_incoming_quota (&address->peer, bandwidth_in);
812       send_outbound_quota (&address->peer, bandwidth_out);
813     }    
814     return;
815   }
816   free_address (na);
817   if (NULL == session)
818     session = papi->get_session (papi->cls, address);    
819   if (NULL == session)
820   {
821     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
822                 "Failed to obtain new session for peer `%s' and  address '%s'\n",
823                 GNUNET_i2s (&address->peer), GST_plugins_a2s (address));    
824     GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
825     return;
826   }
827   na->address = GNUNET_HELLO_address_copy (address);
828   na->bandwidth_in = bandwidth_in;
829   na->bandwidth_out = bandwidth_out;
830   na->session = session;
831   na->ats_active = is_active;
832   if (GNUNET_YES == is_active)
833   {
834     /* Telling ATS about new session */
835     GNUNET_ATS_address_update (GST_ats, na->address, na->session, NULL, 0);
836     GNUNET_ATS_address_in_use (GST_ats, na->address, na->session, GNUNET_YES);
837     GST_validation_set_address_use (na->address, na->session, GNUNET_YES,  __LINE__);
838
839     /* FIXME: is this the right place to set quotas? */
840     GST_neighbours_set_incoming_quota (&address->peer, bandwidth_in);
841     send_outbound_quota (&address->peer, bandwidth_out);
842   }
843 }
844
845
846 /**
847  * Free a neighbour map entry.
848  *
849  * @param n entry to free
850  * @param terminate tell plugin to terminate sessions
851  */
852 static void
853 free_neighbour (struct NeighbourMapEntry *n, int terminate)
854 {
855   struct MessageQueue *mq;
856   struct GNUNET_TRANSPORT_PluginFunctions *papi;
857
858   n->is_active = NULL; /* always free'd by its own continuation! */
859
860   /* fail messages currently in the queue */
861   while (NULL != (mq = n->messages_head))
862   {
863     GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
864     if (NULL != mq->cont)
865       mq->cont (mq->cont_cls, GNUNET_SYSERR);
866     GNUNET_free (mq);
867   }
868   /* It is too late to send other peer disconnect notifications, but at
869      least internally we need to get clean... */
870   if (GNUNET_YES == test_connected (n))
871   {
872     GNUNET_STATISTICS_set (GST_stats, 
873                            gettext_noop ("# peers connected"), 
874                            --neighbours_connected,
875                            GNUNET_NO);
876     disconnect_notify_cb (callback_cls, &n->id);
877   }
878
879   /* FIXME-PLUGIN-API: This does not seem to guarantee that all
880      transport sessions eventually get killed due to inactivity; they
881      MUST have their own timeout logic (but at least TCP doesn't have
882      one yet).  Are we sure that EVERY 'session' of a plugin is
883      actually cleaned up this way!?  Note that if we are switching
884      between two TCP sessions to the same peer, the existing plugin
885      API gives us not even the means to selectively kill only one of
886      them! Killing all sessions like this seems to be very, very
887      wrong. */
888   if ((GNUNET_YES == terminate) &&
889       (NULL != n->primary_address.address) &&
890       (NULL != (papi = GST_plugins_find (n->primary_address.address->transport_name))))
891     papi->disconnect (papi->cls, &n->id);
892
893   n->state = S_DISCONNECT_FINISHED;
894
895   GNUNET_assert (GNUNET_YES ==
896                  GNUNET_CONTAINER_multihashmap_remove (neighbours,
897                                                        &n->id.hashPubKey, n));
898
899   /* cut transport-level connection */
900   free_address (&n->primary_address);
901   free_address (&n->alternative_address);
902
903   // FIXME-ATS-API: we might want to be more specific about
904   // which states we do this from in the future (ATS should
905   // have given us a 'suggest_address' handle, and if we have
906   // such a handle, we should cancel the operation here!
907   GNUNET_ATS_suggest_address_cancel (GST_ats, &n->id);
908
909   if (GNUNET_SCHEDULER_NO_TASK != n->task)
910   {
911     GNUNET_SCHEDULER_cancel (n->task);
912     n->task = GNUNET_SCHEDULER_NO_TASK;
913   }
914   /* free rest of memory */
915   GNUNET_free (n);
916 }
917
918
919 /**
920  * Transmit a message using the current session of the given
921  * neighbour.
922  *
923  * @param n entry for the recipient
924  * @param msgbuf buffer to transmit
925  * @param msgbuf_size number of bytes in buffer
926  * @param priority transmission priority
927  * @param timeout transmission timeout
928  * @param cont continuation to call when finished (can be NULL)
929  * @param cont_cls closure for cont
930  */
931 static void
932 send_with_session (struct NeighbourMapEntry *n,
933                    const char *msgbuf, size_t msgbuf_size,
934                    uint32_t priority,
935                    struct GNUNET_TIME_Relative timeout,
936                    GNUNET_TRANSPORT_TransmitContinuation cont,
937                    void *cont_cls)
938 {
939   struct GNUNET_TRANSPORT_PluginFunctions *papi;
940
941   GNUNET_assert (n->primary_address.session != NULL);
942   if ( ( (NULL == (papi = GST_plugins_find (n->primary_address.address->transport_name))) ||
943          (-1 == papi->send (papi->cls,
944                             n->primary_address.session,
945                             msgbuf, msgbuf_size,
946                             priority,
947                             timeout,
948                             cont, cont_cls))) &&
949        (NULL != cont) )
950     cont (cont_cls, &n->id, GNUNET_SYSERR);
951   GNUNET_break (NULL != papi);
952 }
953
954
955 /**
956  * Master task run for every neighbour.  Performs all of the time-related
957  * activities (keep alive, send next message, disconnect if idle, finish
958  * clean up after disconnect).
959  *
960  * @param cls the 'struct NeighbourMapEntry' for which we are running
961  * @param tc scheduler context (unused)
962  */
963 static void
964 master_task (void *cls,
965              const struct GNUNET_SCHEDULER_TaskContext *tc);
966
967
968 /**
969  * Function called when the 'DISCONNECT' message has been sent by the
970  * plugin.  Frees the neighbour --- if the entry still exists.
971  *
972  * @param cls NULL
973  * @param target identity of the neighbour that was disconnected
974  * @param result GNUNET_OK if the disconnect got out successfully
975  */
976 static void
977 send_disconnect_cont (void *cls, const struct GNUNET_PeerIdentity *target,
978                       int result)
979 {
980   struct NeighbourMapEntry *n;
981
982   n = lookup_neighbour (target);
983   if (NULL == n)
984     return; /* already gone */
985   if (S_DISCONNECT != n->state)
986     return; /* have created a fresh entry since */
987   n->state = S_DISCONNECT;
988   GNUNET_SCHEDULER_cancel (n->task);
989   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
990 }
991
992
993 /**
994  * Transmit a DISCONNECT message to the other peer.
995  *
996  * @param n neighbour to send DISCONNECT message.
997  */
998 static void
999 send_disconnect (struct NeighbourMapEntry *n)
1000 {
1001   struct SessionDisconnectMessage disconnect_msg;
1002
1003   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1004               "Sending DISCONNECT message to peer `%4s'\n",
1005               GNUNET_i2s (&n->id));
1006   disconnect_msg.header.size = htons (sizeof (struct SessionDisconnectMessage));
1007   disconnect_msg.header.type =
1008       htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT);
1009   disconnect_msg.reserved = htonl (0);
1010   disconnect_msg.purpose.size =
1011       htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
1012              sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
1013              sizeof (struct GNUNET_TIME_AbsoluteNBO));
1014   disconnect_msg.purpose.purpose =
1015       htonl (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT);
1016   disconnect_msg.timestamp =
1017       GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1018   disconnect_msg.public_key = GST_my_public_key;
1019   GNUNET_assert (GNUNET_OK ==
1020                  GNUNET_CRYPTO_rsa_sign (GST_my_private_key,
1021                                          &disconnect_msg.purpose,
1022                                          &disconnect_msg.signature));
1023
1024   send_with_session (n,
1025                      (const char *) &disconnect_msg, sizeof (disconnect_msg),
1026                      UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_REL,
1027                      &send_disconnect_cont, NULL);
1028   GNUNET_STATISTICS_update (GST_stats,
1029                             gettext_noop
1030                             ("# DISCONNECT messages sent"), 1,
1031                             GNUNET_NO);
1032 }
1033
1034
1035 /**
1036  * Disconnect from the given neighbour, clean up the record.
1037  *
1038  * @param n neighbour to disconnect from
1039  */
1040 static void
1041 disconnect_neighbour (struct NeighbourMapEntry *n)
1042 {
1043   /* depending on state, notify neighbour and/or upper layers of this peer 
1044      about disconnect */
1045   switch (n->state)
1046   {
1047   case S_NOT_CONNECTED:
1048   case S_INIT_ATS:
1049   case S_INIT_BLACKLIST:
1050     /* other peer is completely unaware of us, no need to send DISCONNECT */
1051     n->state = S_DISCONNECT_FINISHED;
1052     free_neighbour (n, GNUNET_NO);
1053     return;
1054   case S_CONNECT_SENT:
1055     send_disconnect (n); 
1056     n->state = S_DISCONNECT;
1057     break;   
1058   case S_CONNECT_RECV_ATS:
1059   case S_CONNECT_RECV_BLACKLIST:
1060     /* we never ACK'ed the other peer's request, no need to send DISCONNECT */
1061     n->state = S_DISCONNECT_FINISHED;
1062     free_neighbour (n, GNUNET_NO);
1063     return;
1064   case S_CONNECT_RECV_ACK:
1065     /* we DID ACK the other peer's request, must send DISCONNECT */
1066     send_disconnect (n); 
1067     n->state = S_DISCONNECT;
1068     break;   
1069   case S_CONNECTED:
1070   case S_RECONNECT_BLACKLIST:
1071   case S_RECONNECT_SENT:
1072   case S_CONNECTED_SWITCHING_BLACKLIST:
1073   case S_CONNECTED_SWITCHING_CONNECT_SENT:
1074     /* we are currently connected, need to send disconnect and do
1075        internal notifications and update statistics */
1076     send_disconnect (n);
1077     GNUNET_STATISTICS_set (GST_stats, 
1078                            gettext_noop ("# peers connected"), 
1079                            --neighbours_connected,
1080                            GNUNET_NO);
1081     disconnect_notify_cb (callback_cls, &n->id);
1082     n->state = S_DISCONNECT;
1083     break;
1084   case S_RECONNECT_ATS:
1085     /* ATS address request timeout, disconnect without sending disconnect message */
1086     GNUNET_STATISTICS_set (GST_stats,
1087                            gettext_noop ("# peers connected"),
1088                            --neighbours_connected,
1089                            GNUNET_NO);
1090     disconnect_notify_cb (callback_cls, &n->id);
1091     n->state = S_DISCONNECT;
1092     break;
1093   case S_DISCONNECT:
1094     /* already disconnected, ignore */
1095     break;
1096   case S_DISCONNECT_FINISHED:
1097     /* already cleaned up, how did we get here!? */
1098     GNUNET_assert (0);
1099     break;
1100   default:
1101     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
1102     GNUNET_break (0);
1103     break;
1104   }
1105   /* schedule timeout to clean up */
1106   if (GNUNET_SCHEDULER_NO_TASK != n->task)
1107     GNUNET_SCHEDULER_cancel (n->task);
1108   n->task = GNUNET_SCHEDULER_add_delayed (DISCONNECT_SENT_TIMEOUT,
1109                                           &master_task, n);
1110 }
1111
1112
1113 /**
1114  * We're done with our transmission attempt, continue processing.
1115  *
1116  * @param cls the 'struct MessageQueue' of the message
1117  * @param receiver intended receiver
1118  * @param success whether it worked or not
1119  */
1120 static void
1121 transmit_send_continuation (void *cls,
1122                             const struct GNUNET_PeerIdentity *receiver,
1123                             int success)
1124 {
1125   struct MessageQueue *mq = cls;
1126   struct NeighbourMapEntry *n;
1127
1128   if (NULL == (n = lookup_neighbour (receiver)))
1129     return; /* disconnect or other error while transmitting, can happen */
1130   if (n->is_active == mq)
1131   {
1132     /* this is still "our" neighbour, remove us from its queue
1133        and allow it to send the next message now */
1134     n->is_active = NULL;
1135     GNUNET_SCHEDULER_cancel (n->task);
1136     n->task = GNUNET_SCHEDULER_add_now (&master_task, n);    
1137   }
1138   GNUNET_assert (bytes_in_send_queue >= mq->message_buf_size);
1139   bytes_in_send_queue -= mq->message_buf_size;
1140   GNUNET_STATISTICS_set (GST_stats,
1141                         gettext_noop
1142                          ("# bytes in message queue for other peers"),
1143                          bytes_in_send_queue, GNUNET_NO);
1144   if (GNUNET_OK == success)
1145     GNUNET_STATISTICS_update (GST_stats,
1146                               gettext_noop
1147                               ("# messages transmitted to other peers"),
1148                               1, GNUNET_NO);
1149   else
1150     GNUNET_STATISTICS_update (GST_stats,
1151                               gettext_noop
1152                               ("# transmission failures for messages to other peers"),
1153                               1, GNUNET_NO);
1154   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1155               "Sending message to `%s' of type %u was a %s\n",
1156               GNUNET_i2s (receiver),
1157               ntohs (((struct GNUNET_MessageHeader *) mq->message_buf)->type),
1158               (success == GNUNET_OK) ? "success" : "FAILURE");
1159   if (NULL != mq->cont)
1160     mq->cont (mq->cont_cls, success);
1161   GNUNET_free (mq);
1162 }
1163
1164
1165 /**
1166  * Check the message list for the given neighbour and if we can
1167  * send a message, do so.  This function should only be called
1168  * if the connection is at least generally ready for transmission.
1169  * While we will only send one message at a time, no bandwidth
1170  * quota management is performed here.  If a message was given to
1171  * the plugin, the continuation will automatically re-schedule
1172  * the 'master' task once the next message might be transmitted.
1173  *
1174  * @param n target peer for which to transmit
1175  */
1176 static void
1177 try_transmission_to_peer (struct NeighbourMapEntry *n)
1178 {
1179   struct MessageQueue *mq;
1180   struct GNUNET_TIME_Relative timeout;
1181
1182   if (NULL == n->primary_address.address)
1183   {
1184     /* no address, why are we here? */
1185     GNUNET_break (0);
1186     return;
1187   }
1188   if ((0 == n->primary_address.address->address_length) && 
1189       (NULL == n->primary_address.session))
1190   {
1191     /* no address, why are we here? */
1192     GNUNET_break (0);
1193     return;
1194   }
1195   if (NULL != n->is_active)
1196   {
1197     /* transmission already pending */
1198     return;                     
1199   }
1200
1201   /* timeout messages from the queue that are past their due date */
1202   while (NULL != (mq = n->messages_head))
1203   {
1204     timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1205     if (timeout.rel_value > 0)
1206       break;
1207     GNUNET_STATISTICS_update (GST_stats,
1208                               gettext_noop
1209                               ("# messages timed out while in transport queue"),
1210                               1, GNUNET_NO);
1211     GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
1212     n->is_active = mq;
1213     transmit_send_continuation (mq, &n->id, GNUNET_SYSERR);     /* timeout */
1214   }
1215   if (NULL == mq)
1216     return;                     /* no more messages */
1217   GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
1218   n->is_active = mq;
1219   send_with_session (n,
1220                      mq->message_buf, mq->message_buf_size,
1221                      0 /* priority */, timeout,
1222                      &transmit_send_continuation, mq);
1223 }
1224
1225
1226 /**
1227  * Send keepalive message to the neighbour.  Must only be called
1228  * if we are on 'connected' state.  Will internally determine
1229  * if a keepalive is truly needed (so can always be called).
1230  *
1231  * @param n neighbour that went idle and needs a keepalive
1232  */
1233 static void
1234 send_keepalive (struct NeighbourMapEntry *n)
1235 {
1236   struct GNUNET_MessageHeader m;
1237
1238   GNUNET_assert (S_CONNECTED == n->state);
1239   if (GNUNET_TIME_absolute_get_remaining (n->keep_alive_time).rel_value > 0)
1240     return; /* no keepalive needed at this time */
1241   m.size = htons (sizeof (struct GNUNET_MessageHeader));
1242   m.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE);
1243   send_with_session (n,
1244                      (const void *) &m, sizeof (m),
1245                      UINT32_MAX /* priority */,
1246                      KEEPALIVE_FREQUENCY,
1247                      NULL, NULL);
1248   GNUNET_STATISTICS_update (GST_stats, gettext_noop ("# keepalives sent"), 1,
1249                             GNUNET_NO);
1250   n->expect_latency_response = GNUNET_YES;
1251   n->last_keep_alive_time = GNUNET_TIME_absolute_get ();
1252   n->keep_alive_time = GNUNET_TIME_relative_to_absolute (KEEPALIVE_FREQUENCY);
1253 }
1254
1255
1256 /**
1257  * Keep the connection to the given neighbour alive longer,
1258  * we received a KEEPALIVE (or equivalent); send a response.
1259  *
1260  * @param neighbour neighbour to keep alive (by sending keep alive response)
1261  */
1262 void
1263 GST_neighbours_keepalive (const struct GNUNET_PeerIdentity *neighbour)
1264 {
1265   struct NeighbourMapEntry *n;
1266   struct GNUNET_MessageHeader m;
1267
1268   if (NULL == (n = lookup_neighbour (neighbour)))
1269   {
1270     GNUNET_STATISTICS_update (GST_stats,
1271                               gettext_noop
1272                               ("# KEEPALIVE messages discarded (peer unknown)"),
1273                               1, GNUNET_NO);
1274     return;
1275   }
1276   if (NULL == n->primary_address.session)
1277   {
1278     GNUNET_STATISTICS_update (GST_stats,
1279                               gettext_noop
1280                               ("# KEEPALIVE messages discarded (no session)"),
1281                               1, GNUNET_NO);
1282     return;
1283   }
1284   /* send reply to allow neighbour to measure latency */
1285   m.size = htons (sizeof (struct GNUNET_MessageHeader));
1286   m.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE_RESPONSE);
1287   send_with_session(n,
1288                     (const void *) &m, sizeof (m),
1289                     UINT32_MAX /* priority */,
1290                     KEEPALIVE_FREQUENCY,
1291                     NULL, NULL);
1292 }
1293
1294
1295 /**
1296  * We received a KEEP_ALIVE_RESPONSE message and use this to calculate
1297  * latency to this peer.  Pass the updated information (existing ats
1298  * plus calculated latency) to ATS.
1299  *
1300  * @param neighbour neighbour to keep alive
1301  * @param ats performance data
1302  * @param ats_count number of entries in ats
1303  */
1304 void
1305 GST_neighbours_keepalive_response (const struct GNUNET_PeerIdentity *neighbour,
1306                                    const struct GNUNET_ATS_Information *ats,
1307                                    uint32_t ats_count)
1308 {
1309   struct NeighbourMapEntry *n;
1310   uint32_t latency;
1311   struct GNUNET_ATS_Information ats_new[ats_count + 1];
1312
1313   if (NULL == (n = lookup_neighbour (neighbour)))
1314   {
1315     GNUNET_STATISTICS_update (GST_stats,
1316                               gettext_noop
1317                               ("# KEEPALIVE_RESPONSE messages discarded (not connected)"),
1318                               1, GNUNET_NO);
1319     return;
1320   }
1321   if ( (S_CONNECTED != n->state) ||
1322        (GNUNET_YES != n->expect_latency_response) )
1323   {
1324     GNUNET_STATISTICS_update (GST_stats,
1325                               gettext_noop
1326                               ("# KEEPALIVE_RESPONSE messages discarded (not expected)"),
1327                               1, GNUNET_NO);
1328     return;
1329   }
1330   n->expect_latency_response = GNUNET_NO;
1331   n->latency = GNUNET_TIME_absolute_get_duration (n->last_keep_alive_time);
1332   n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1333   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1334               "Latency for peer `%s' is %llu ms\n",
1335               GNUNET_i2s (&n->id), n->latency.rel_value);
1336   memcpy (ats_new, ats, sizeof (struct GNUNET_ATS_Information) * ats_count);
1337   /* append latency */
1338   ats_new[ats_count].type = htonl (GNUNET_ATS_QUALITY_NET_DELAY);
1339   if (n->latency.rel_value > UINT32_MAX)
1340     latency = UINT32_MAX;
1341   else
1342     latency = n->latency.rel_value;
1343   ats_new[ats_count].value = htonl (latency);
1344   GNUNET_ATS_address_update (GST_ats, 
1345                              n->primary_address.address, 
1346                              n->primary_address.session, ats_new,
1347                              ats_count + 1);
1348 }
1349
1350
1351 /**
1352  * We have received a message from the given sender.  How long should
1353  * we delay before receiving more?  (Also used to keep the peer marked
1354  * as live).
1355  *
1356  * @param sender sender of the message
1357  * @param size size of the message
1358  * @param do_forward set to GNUNET_YES if the message should be forwarded to clients
1359  *                   GNUNET_NO if the neighbour is not connected or violates the quota,
1360  *                   GNUNET_SYSERR if the connection is not fully up yet
1361  * @return how long to wait before reading more from this sender
1362  */
1363 struct GNUNET_TIME_Relative
1364 GST_neighbours_calculate_receive_delay (const struct GNUNET_PeerIdentity
1365                                         *sender, ssize_t size, int *do_forward)
1366 {
1367   struct NeighbourMapEntry *n;
1368   struct GNUNET_TIME_Relative ret;
1369   
1370   if (NULL == neighbours)
1371   {
1372     *do_forward = GNUNET_NO;
1373     return GNUNET_TIME_UNIT_FOREVER_REL; /* This can happen during shutdown */
1374   }
1375   if (NULL == (n = lookup_neighbour (sender)))
1376   {
1377     GST_neighbours_try_connect (sender);
1378     if (NULL == (n = lookup_neighbour (sender)))
1379     {
1380       GNUNET_STATISTICS_update (GST_stats,
1381                                 gettext_noop
1382                                 ("# messages discarded due to lack of neighbour record"),
1383                                 1, GNUNET_NO);
1384       *do_forward = GNUNET_NO;
1385       return GNUNET_TIME_UNIT_ZERO;
1386     }
1387   }
1388   if (! test_connected (n))
1389   {
1390     *do_forward = GNUNET_SYSERR;
1391     return GNUNET_TIME_UNIT_ZERO;
1392   }
1393   if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, size))
1394   {
1395     n->quota_violation_count++;
1396     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1397                 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
1398                 n->in_tracker.available_bytes_per_s__,
1399                 n->quota_violation_count);
1400     /* Discount 32k per violation */
1401     GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, -32 * 1024);
1402   }
1403   else
1404   {
1405     if (n->quota_violation_count > 0)
1406     {
1407       /* try to add 32k back */
1408       GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, 32 * 1024);
1409       n->quota_violation_count--;
1410     }
1411   }
1412   if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
1413   {
1414     GNUNET_STATISTICS_update (GST_stats,
1415                               gettext_noop
1416                               ("# bandwidth quota violations by other peers"),
1417                               1, GNUNET_NO);
1418     *do_forward = GNUNET_NO;
1419     return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
1420   }
1421   *do_forward = GNUNET_YES;
1422   ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 32 * 1024);
1423   if (ret.rel_value > 0)
1424   {
1425     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1426                 "Throttling read (%llu bytes excess at %u b/s), waiting %llu ms before reading more.\n",
1427                 (unsigned long long) n->in_tracker.
1428                 consumption_since_last_update__,
1429                 (unsigned int) n->in_tracker.available_bytes_per_s__,
1430                 (unsigned long long) ret.rel_value);
1431     GNUNET_STATISTICS_update (GST_stats,
1432                               gettext_noop ("# ms throttling suggested"),
1433                               (int64_t) ret.rel_value, GNUNET_NO);
1434   }
1435   return ret;
1436 }
1437
1438
1439 /**
1440  * Transmit a message to the given target using the active connection.
1441  *
1442  * @param target destination
1443  * @param msg message to send
1444  * @param msg_size number of bytes in msg
1445  * @param timeout when to fail with timeout
1446  * @param cont function to call when done
1447  * @param cont_cls closure for 'cont'
1448  */
1449 void
1450 GST_neighbours_send (const struct GNUNET_PeerIdentity *target, const void *msg,
1451                      size_t msg_size, struct GNUNET_TIME_Relative timeout,
1452                      GST_NeighbourSendContinuation cont, void *cont_cls)
1453 {
1454   struct NeighbourMapEntry *n;
1455   struct MessageQueue *mq;
1456
1457   /* All ove these cases should never happen; they are all API violations.
1458      But we check anyway, just to be sure. */
1459   if (NULL == (n = lookup_neighbour (target)))
1460   {
1461     GNUNET_break (0);
1462     if (NULL != cont)
1463       cont (cont_cls, GNUNET_SYSERR);
1464     return;
1465   }
1466   if (GNUNET_YES != test_connected (n))
1467   {
1468     GNUNET_break (0);
1469     if (NULL != cont)
1470       cont (cont_cls, GNUNET_SYSERR);
1471     return;
1472   }
1473   bytes_in_send_queue += msg_size;
1474   GNUNET_STATISTICS_set (GST_stats,
1475                          gettext_noop
1476                          ("# bytes in message queue for other peers"),
1477                          bytes_in_send_queue, GNUNET_NO);
1478   mq = GNUNET_malloc (sizeof (struct MessageQueue) + msg_size);
1479   mq->cont = cont;
1480   mq->cont_cls = cont_cls;
1481   memcpy (&mq[1], msg, msg_size);
1482   mq->message_buf = (const char *) &mq[1];
1483   mq->message_buf_size = msg_size;
1484   mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1485   GNUNET_CONTAINER_DLL_insert_tail (n->messages_head, n->messages_tail, mq);
1486   if ( (NULL != n->is_active) ||
1487        ( (NULL == n->primary_address.session) && (NULL == n->primary_address.address)) )
1488     return;
1489   GNUNET_SCHEDULER_cancel (n->task);
1490   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
1491 }
1492
1493
1494 /**
1495  * Send a SESSION_CONNECT message via the given address.
1496  *
1497  * @param na address to use
1498  */
1499 static void
1500 send_session_connect (struct NeighbourAddress *na)
1501 {
1502   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1503   struct SessionConnectMessage connect_msg;
1504   
1505   if (NULL == (papi = GST_plugins_find (na->address->transport_name)))  
1506   {
1507     GNUNET_break (0);
1508     return;
1509   }
1510   if (NULL == na->session)
1511     na->session = papi->get_session (papi->cls, na->address);    
1512   if (NULL == na->session)
1513   {
1514     GNUNET_break (0);
1515     return;
1516   }
1517   na->connect_timestamp = GNUNET_TIME_absolute_get ();
1518   connect_msg.header.size = htons (sizeof (struct SessionConnectMessage));
1519   connect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT);
1520   connect_msg.reserved = htonl (0);
1521   connect_msg.timestamp = GNUNET_TIME_absolute_hton (na->connect_timestamp);
1522   (void) papi->send (papi->cls,
1523                      na->session,
1524                      (const char *) &connect_msg, sizeof (struct SessionConnectMessage),
1525                      UINT_MAX,
1526                      GNUNET_TIME_UNIT_FOREVER_REL,
1527                      NULL, NULL);
1528 }
1529
1530
1531 /**
1532  * Send a SESSION_CONNECT_ACK message via the given address.
1533  *
1534  * @param address address to use
1535  * @param session session to use
1536  * @param timestamp timestamp to use for the ACK message
1537  */
1538 static void
1539 send_session_connect_ack_message (const struct GNUNET_HELLO_Address *address,
1540                                   struct Session *session,
1541                                   struct GNUNET_TIME_Absolute timestamp)
1542 {
1543   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1544   struct SessionConnectMessage connect_msg;
1545   
1546   if (NULL == (papi = GST_plugins_find (address->transport_name)))  
1547   {
1548     GNUNET_break (0);
1549     return;
1550   }
1551   if (NULL == session)
1552     session = papi->get_session (papi->cls, address);    
1553   if (NULL == session)
1554   {
1555     GNUNET_break (0);
1556     return;
1557   }
1558   connect_msg.header.size = htons (sizeof (struct SessionConnectMessage));
1559   connect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT_ACK);
1560   connect_msg.reserved = htonl (0);
1561   connect_msg.timestamp = GNUNET_TIME_absolute_hton (timestamp);
1562   (void) papi->send (papi->cls,
1563                      session,
1564                      (const char *) &connect_msg, sizeof (struct SessionConnectMessage),
1565                      UINT_MAX,
1566                      GNUNET_TIME_UNIT_FOREVER_REL,
1567                      NULL, NULL);
1568 }
1569
1570
1571 /**
1572  * Create a fresh entry in the neighbour map for the given peer
1573  *
1574  * @param peer peer to create an entry for
1575  * @return new neighbour map entry
1576  */
1577 static struct NeighbourMapEntry *
1578 setup_neighbour (const struct GNUNET_PeerIdentity *peer)
1579 {
1580   struct NeighbourMapEntry *n;
1581
1582   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1583               "Creating new neighbour entry for `%s'\n", 
1584               GNUNET_i2s (peer));
1585   n = GNUNET_malloc (sizeof (struct NeighbourMapEntry));
1586   n->id = *peer;
1587   n->state = S_NOT_CONNECTED;
1588   n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
1589   GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
1590                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
1591                                  MAX_BANDWIDTH_CARRY_S);
1592   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
1593   GNUNET_assert (GNUNET_OK ==
1594                  GNUNET_CONTAINER_multihashmap_put (neighbours,
1595                                                     &n->id.hashPubKey, n,
1596                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1597   return n;
1598 }
1599
1600
1601 /**
1602  * Check if the two given addresses are the same.
1603  * Actually only checks if the sessions are non-NULL
1604  * (which they should be) and then if they are identical;
1605  * the actual addresses don't matter if the session
1606  * pointers match anyway, and we must have session pointers
1607  * at this time.
1608  *
1609  * @param a1 first address to compare
1610  * @param a2 other address to compare
1611  * @return GNUNET_NO if the addresses do not match, GNUNET_YES if they do match
1612  */
1613 static int
1614 address_matches (const struct NeighbourAddress *a1,
1615                  const struct NeighbourAddress *a2)
1616 {
1617   if ( (NULL == a1->session) ||
1618        (NULL == a2->session) )
1619   {
1620     GNUNET_break (0);
1621     return 0;
1622   }
1623   return (a1->session == a2->session) ? GNUNET_YES : GNUNET_NO;
1624 }
1625
1626
1627 /**
1628  * Try to create a connection to the given target (eventually).
1629  *
1630  * @param target peer to try to connect to
1631  */
1632 void
1633 GST_neighbours_try_connect (const struct GNUNET_PeerIdentity *target)
1634 {
1635   struct NeighbourMapEntry *n;
1636
1637   if (NULL == neighbours)  
1638     return; /* during shutdown, do nothing */
1639   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1640               "Asked to connect to peer `%s'\n",
1641               GNUNET_i2s (target));
1642   if (0 ==
1643       memcmp (target, &GST_my_identity, sizeof (struct GNUNET_PeerIdentity)))
1644   {
1645     /* refuse to connect to myself */
1646     /* FIXME: can this happen? Is this not an API violation? */
1647     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1648                 "Refusing to try to connect to myself.\n");
1649     return;
1650   }
1651   n = lookup_neighbour (target);
1652   if (NULL != n)
1653   {
1654     switch (n->state)
1655     {
1656     case S_NOT_CONNECTED:
1657       /* this should not be possible */
1658       GNUNET_break (0);
1659       free_neighbour (n, GNUNET_NO);
1660       break;
1661     case S_INIT_ATS:
1662     case S_INIT_BLACKLIST:
1663     case S_CONNECT_SENT:
1664     case S_CONNECT_RECV_ATS:
1665     case S_CONNECT_RECV_BLACKLIST:
1666     case S_CONNECT_RECV_ACK:
1667       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1668                   "Ignoring request to try to connect to `%s', already trying!\n",
1669                   GNUNET_i2s (target));
1670       return; /* already trying */
1671     case S_CONNECTED:      
1672     case S_RECONNECT_ATS:
1673     case S_RECONNECT_BLACKLIST:
1674     case S_RECONNECT_SENT:
1675     case S_CONNECTED_SWITCHING_BLACKLIST:
1676     case S_CONNECTED_SWITCHING_CONNECT_SENT:
1677       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1678                   "Ignoring request to try to connect, already connected to `%s'!\n",
1679                   GNUNET_i2s (target));
1680       return; /* already connected */
1681     case S_DISCONNECT:
1682       /* get rid of remains, ready to re-try immediately */
1683       free_neighbour (n, GNUNET_NO);
1684       break;
1685     case S_DISCONNECT_FINISHED:
1686       /* should not be possible */      
1687       GNUNET_assert (0); 
1688     default:
1689       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
1690       GNUNET_break (0);
1691       free_neighbour (n, GNUNET_NO);
1692       break;
1693     }
1694   }
1695   n = setup_neighbour (target);  
1696   n->state = S_INIT_ATS; 
1697   n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1698
1699   GNUNET_ATS_reset_backoff (GST_ats, target);
1700   GNUNET_ATS_suggest_address (GST_ats, target);
1701 }
1702
1703
1704 /**
1705  * Function called with the result of a blacklist check.
1706  *
1707  * @param cls closure with the 'struct BlackListCheckContext'
1708  * @param peer peer this check affects
1709  * @param result GNUNET_OK if the address is allowed
1710  */
1711 static void
1712 handle_test_blacklist_cont (void *cls,
1713                             const struct GNUNET_PeerIdentity *peer,
1714                             int result)
1715 {
1716   struct BlackListCheckContext *bcc = cls;
1717   struct NeighbourMapEntry *n;
1718
1719   bcc->bc = NULL;
1720   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1721               "Connection to new address of peer `%s' based on blacklist is `%s'\n",
1722               GNUNET_i2s (peer),
1723               (GNUNET_OK == result) ? "allowed" : "FORBIDDEN");
1724   if (GNUNET_OK == result)
1725   {
1726     /* valid new address, let ATS know! */
1727     GNUNET_ATS_address_update (GST_ats, 
1728                                bcc->na.address, 
1729                                bcc->na.session, 
1730                                bcc->ats, bcc->ats_count);
1731   }
1732   if (NULL == (n = lookup_neighbour (peer)))
1733     goto cleanup; /* nobody left to care about new address */
1734   switch (n->state)
1735   {
1736   case S_NOT_CONNECTED:
1737     /* this should not be possible */
1738     GNUNET_break (0);
1739     free_neighbour (n, GNUNET_NO);
1740     break;
1741   case S_INIT_ATS:
1742     /* still waiting on ATS suggestion */
1743     break;
1744   case S_INIT_BLACKLIST:
1745     /* check if the address the blacklist was fine with matches
1746        ATS suggestion, if so, we can move on! */
1747     if ( (GNUNET_OK == result) &&
1748          (1 == n->send_connect_ack) )
1749     {
1750       n->send_connect_ack = 2;
1751       send_session_connect_ack_message (bcc->na.address,
1752                                         bcc->na.session,
1753                                         n->connect_ack_timestamp);
1754     }
1755     if (GNUNET_YES != address_matches (&bcc->na, &n->primary_address))
1756       break; /* result for an address we currently don't care about */
1757     if (GNUNET_OK == result)
1758     {
1759       n->timeout = GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT);
1760       n->state = S_CONNECT_SENT;
1761       send_session_connect (&n->primary_address);
1762     }
1763     else
1764     {
1765       GNUNET_ATS_address_destroyed (GST_ats,
1766                                     bcc->na.address,
1767                                     NULL);
1768       n->state = S_INIT_ATS;
1769       n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1770       // FIXME: do we need to ask ATS again for suggestions?
1771       GNUNET_ATS_suggest_address (GST_ats, &n->id);
1772     }
1773     break;
1774   case S_CONNECT_SENT:
1775     /* waiting on CONNECT_ACK, send ACK if one is pending */
1776     if ( (GNUNET_OK == result) &&
1777          (1 == n->send_connect_ack) )
1778     {
1779       n->send_connect_ack = 2;
1780       send_session_connect_ack_message (n->primary_address.address,
1781                                         n->primary_address.session,
1782                                         n->connect_ack_timestamp);
1783     }
1784     break; 
1785   case S_CONNECT_RECV_ATS:
1786     /* still waiting on ATS suggestion, don't care about blacklist */
1787     break; 
1788   case S_CONNECT_RECV_BLACKLIST:
1789     if (GNUNET_YES != address_matches (&bcc->na, &n->primary_address))
1790       break; /* result for an address we currently don't care about */
1791     if (GNUNET_OK == result)
1792     {
1793       n->timeout = GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT);
1794       n->state = S_CONNECT_RECV_ACK;
1795       send_session_connect_ack_message (bcc->na.address,
1796                                         bcc->na.session,
1797                                         n->connect_ack_timestamp);
1798       if (1 == n->send_connect_ack) 
1799         n->send_connect_ack = 2;
1800     }
1801     else
1802     {
1803       GNUNET_ATS_address_destroyed (GST_ats,
1804                                     bcc->na.address,
1805                                     NULL);
1806       n->state = S_INIT_ATS;
1807       n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1808       // FIXME: do we need to ask ATS again for suggestions?
1809       GNUNET_ATS_reset_backoff (GST_ats, peer);
1810       GNUNET_ATS_suggest_address (GST_ats, &n->id);
1811     }
1812     break;
1813   case S_CONNECT_RECV_ACK:
1814     /* waiting on SESSION_ACK, send ACK if one is pending */
1815     if ( (GNUNET_OK == result) &&
1816          (1 == n->send_connect_ack) )
1817     {
1818       n->send_connect_ack = 2;
1819       send_session_connect_ack_message (n->primary_address.address,
1820                                         n->primary_address.session,
1821                                         n->connect_ack_timestamp);
1822     }
1823     break; 
1824   case S_CONNECTED:
1825     /* already connected, don't care about blacklist */
1826     break;
1827   case S_RECONNECT_ATS:
1828     /* still waiting on ATS suggestion, don't care about blacklist */
1829     break;     
1830   case S_RECONNECT_BLACKLIST:
1831     if ( (GNUNET_OK == result) &&
1832          (1 == n->send_connect_ack) )
1833     {
1834       n->send_connect_ack = 2;
1835       send_session_connect_ack_message (bcc->na.address,
1836                                         bcc->na.session,
1837                                         n->connect_ack_timestamp);
1838     }
1839     if (GNUNET_YES != address_matches (&bcc->na, &n->primary_address))
1840       break; /* result for an address we currently don't care about */
1841     if (GNUNET_OK == result)
1842     {
1843       send_session_connect (&n->primary_address);
1844       n->timeout = GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT);
1845       n->state = S_RECONNECT_SENT;
1846     }
1847     else
1848     {
1849       GNUNET_ATS_address_destroyed (GST_ats,
1850                                     bcc->na.address,
1851                                     NULL);
1852       n->state = S_RECONNECT_ATS;
1853       n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1854       // FIXME: do we need to ask ATS again for suggestions?
1855       GNUNET_ATS_suggest_address (GST_ats, &n->id);
1856     }
1857     break;
1858   case S_RECONNECT_SENT:
1859     /* waiting on CONNECT_ACK, don't care about blacklist */
1860     if ( (GNUNET_OK == result) &&
1861          (1 == n->send_connect_ack) )
1862     {
1863       n->send_connect_ack = 2;
1864       send_session_connect_ack_message (n->primary_address.address,
1865                                         n->primary_address.session,
1866                                         n->connect_ack_timestamp);
1867     }
1868     break;     
1869   case S_CONNECTED_SWITCHING_BLACKLIST:
1870     if (GNUNET_YES != address_matches (&bcc->na, &n->alternative_address))
1871       break; /* result for an address we currently don't care about */
1872     if (GNUNET_OK == result)
1873     {
1874       send_session_connect (&n->alternative_address);
1875       n->state = S_CONNECTED_SWITCHING_CONNECT_SENT;
1876     }
1877     else
1878     {
1879       GNUNET_ATS_address_destroyed (GST_ats,
1880                                     bcc->na.address,
1881                                     NULL);
1882       free_address (&n->alternative_address);
1883       n->state = S_CONNECTED;
1884     }
1885     break;
1886   case S_CONNECTED_SWITCHING_CONNECT_SENT:
1887     /* waiting on CONNECT_ACK, don't care about blacklist */
1888     if ( (GNUNET_OK == result) &&
1889          (1 == n->send_connect_ack) )
1890     {
1891       n->send_connect_ack = 2;
1892       send_session_connect_ack_message (n->primary_address.address,
1893                                         n->primary_address.session,
1894                                         n->connect_ack_timestamp);
1895     }
1896     break;     
1897   case S_DISCONNECT:
1898     /* Nothing to do here, ATS will already do what can be done */
1899     break;
1900   case S_DISCONNECT_FINISHED:
1901     /* should not be possible */
1902     GNUNET_assert (0);
1903     break;
1904   default:
1905     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
1906     GNUNET_break (0);
1907     free_neighbour (n, GNUNET_NO);
1908     break;
1909   }
1910  cleanup:
1911   GNUNET_HELLO_address_free (bcc->na.address);
1912   GNUNET_CONTAINER_DLL_remove (bc_head,
1913                                bc_tail,
1914                                bcc);
1915   GNUNET_free (bcc);
1916 }
1917
1918
1919 /**
1920  * We want to know if connecting to a particular peer via
1921  * a particular address is allowed.  Check it!
1922  *
1923  * @param peer identity of the peer to switch the address for
1924  * @param ts time at which the check was initiated
1925  * @param address address of the other peer, NULL if other peer
1926  *                       connected to us
1927  * @param session session to use (or NULL)
1928  * @param ats performance data
1929  * @param ats_count number of entries in ats (excluding 0-termination)
1930  */
1931 static void
1932 check_blacklist (const struct GNUNET_PeerIdentity *peer,
1933                  struct GNUNET_TIME_Absolute ts,
1934                  const struct GNUNET_HELLO_Address *address,
1935                  struct Session *session,
1936                  const struct GNUNET_ATS_Information *ats,
1937                  uint32_t ats_count)
1938 {
1939   struct BlackListCheckContext *bcc;
1940   struct GST_BlacklistCheck *bc;
1941
1942   bcc =
1943       GNUNET_malloc (sizeof (struct BlackListCheckContext) +
1944                      sizeof (struct GNUNET_ATS_Information) * ats_count);
1945   bcc->ats_count = ats_count;
1946   bcc->na.address = GNUNET_HELLO_address_copy (address);
1947   bcc->na.session = session;
1948   bcc->na.connect_timestamp = ts;
1949   bcc->ats = (struct GNUNET_ATS_Information *) &bcc[1];
1950   memcpy (bcc->ats, ats, sizeof (struct GNUNET_ATS_Information) * ats_count);
1951   GNUNET_CONTAINER_DLL_insert (bc_head,
1952                                bc_tail,
1953                                bcc);
1954   if (NULL != (bc = GST_blacklist_test_allowed (peer, 
1955                                                 address->transport_name,
1956                                                 &handle_test_blacklist_cont, bcc)))
1957     bcc->bc = bc; 
1958   /* if NULL == bc, 'cont' was already called and 'bcc' already free'd, so
1959      we must only store 'bc' if 'bc' is non-NULL... */
1960 }
1961
1962
1963 /**
1964  * We received a 'SESSION_CONNECT' message from the other peer.
1965  * Consider switching to it.
1966  *
1967  * @param message possibly a 'struct SessionConnectMessage' (check format)
1968  * @param peer identity of the peer to switch the address for
1969  * @param address address of the other peer, NULL if other peer
1970  *                       connected to us
1971  * @param session session to use (or NULL)
1972  * @param ats performance data
1973  * @param ats_count number of entries in ats (excluding 0-termination)
1974  */
1975 void
1976 GST_neighbours_handle_connect (const struct GNUNET_MessageHeader *message,
1977                                const struct GNUNET_PeerIdentity *peer,
1978                                const struct GNUNET_HELLO_Address *address,
1979                                struct Session *session,
1980                                const struct GNUNET_ATS_Information *ats,
1981                                uint32_t ats_count)
1982 {
1983   const struct SessionConnectMessage *scm;
1984   struct NeighbourMapEntry *n;
1985   struct GNUNET_TIME_Absolute ts;
1986
1987   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1988               "Received CONNECT message from peer `%s'\n", 
1989               GNUNET_i2s (peer));
1990   if (ntohs (message->size) != sizeof (struct SessionConnectMessage))
1991   {
1992     GNUNET_break_op (0);
1993     return;
1994   }
1995   if (NULL == neighbours)
1996     return; /* we're shutting down */
1997   scm = (const struct SessionConnectMessage *) message;
1998   GNUNET_break_op (0 == ntohl (scm->reserved));
1999   ts = GNUNET_TIME_absolute_ntoh (scm->timestamp);
2000   n = lookup_neighbour (peer);
2001   if (NULL == n)
2002     n = setup_neighbour (peer);
2003   n->send_connect_ack = 1;
2004   n->connect_ack_timestamp = ts;
2005   switch (n->state)
2006   {  
2007   case S_NOT_CONNECTED:
2008     n->state = S_CONNECT_RECV_ATS;
2009     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
2010     GNUNET_ATS_reset_backoff (GST_ats, peer);
2011     GNUNET_ATS_suggest_address (GST_ats, peer);
2012     check_blacklist (peer, ts, address, session, ats, ats_count);
2013     break;
2014   case S_INIT_ATS:
2015   case S_INIT_BLACKLIST:
2016   case S_CONNECT_SENT:
2017   case S_CONNECT_RECV_ATS:
2018   case S_CONNECT_RECV_BLACKLIST:
2019   case S_CONNECT_RECV_ACK:
2020     /* It can never hurt to have an alternative address in the above cases, 
2021        see if it is allowed */
2022     check_blacklist (peer, ts, address, session, ats, ats_count);
2023     break;
2024   case S_CONNECTED:
2025     /* we are already connected and can thus send the ACK immediately;
2026        still, it can never hurt to have an alternative address, so also
2027        tell ATS  about it */
2028     GNUNET_assert (NULL != n->primary_address.address);
2029     GNUNET_assert (NULL != n->primary_address.session);
2030     n->send_connect_ack = 0;
2031     send_session_connect_ack_message (n->primary_address.address,
2032                                       n->primary_address.session, ts);
2033     check_blacklist (peer, ts, address, session, ats, ats_count);
2034     break;
2035   case S_RECONNECT_ATS:
2036   case S_RECONNECT_BLACKLIST:
2037   case S_RECONNECT_SENT:
2038     /* It can never hurt to have an alternative address in the above cases, 
2039        see if it is allowed */
2040     check_blacklist (peer, ts, address, session, ats, ats_count);
2041     break;
2042   case S_CONNECTED_SWITCHING_BLACKLIST:
2043   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2044     /* we are already connected and can thus send the ACK immediately;
2045        still, it can never hurt to have an alternative address, so also
2046        tell ATS  about it */
2047     GNUNET_assert (NULL != n->primary_address.address);
2048     GNUNET_assert (NULL != n->primary_address.session);
2049     n->send_connect_ack = 0;
2050     send_session_connect_ack_message (n->primary_address.address,
2051                                       n->primary_address.session, ts);
2052     check_blacklist (peer, ts, address, session, ats, ats_count);
2053     break;
2054   case S_DISCONNECT:
2055     /* get rid of remains without terminating sessions, ready to re-try */
2056     free_neighbour (n, GNUNET_YES);
2057     n = setup_neighbour (peer);
2058     n->state = S_CONNECT_RECV_ATS;
2059     GNUNET_ATS_reset_backoff (GST_ats, peer);
2060     GNUNET_ATS_suggest_address (GST_ats, peer);
2061     break;
2062   case S_DISCONNECT_FINISHED:
2063     /* should not be possible */
2064     GNUNET_assert (0);
2065     break;
2066   default:
2067     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2068     GNUNET_break (0);
2069     free_neighbour (n, GNUNET_NO);
2070     break;
2071   }
2072 }
2073
2074
2075 /**
2076  * For an existing neighbour record, set the active connection to
2077  * use the given address.  
2078  *
2079  * @param peer identity of the peer to switch the address for
2080  * @param address address of the other peer, NULL if other peer
2081  *                       connected to us
2082  * @param session session to use (or NULL)
2083  * @param ats performance data
2084  * @param ats_count number of entries in ats
2085  * @param bandwidth_in inbound quota to be used when connection is up
2086  * @param bandwidth_out outbound quota to be used when connection is up
2087  */
2088 void
2089 GST_neighbours_switch_to_address (const struct GNUNET_PeerIdentity *peer,
2090                                   const struct GNUNET_HELLO_Address *address,
2091                                   struct Session *session,
2092                                   const struct GNUNET_ATS_Information *ats,
2093                                   uint32_t ats_count,
2094                                   struct GNUNET_BANDWIDTH_Value32NBO
2095                                   bandwidth_in,
2096                                   struct GNUNET_BANDWIDTH_Value32NBO
2097                                   bandwidth_out)
2098 {
2099   struct NeighbourMapEntry *n;
2100   struct GNUNET_TRANSPORT_PluginFunctions *papi;
2101
2102   GNUNET_assert (address->transport_name != NULL);
2103   if (NULL == (n = lookup_neighbour (peer)))
2104     return;
2105
2106   /* Obtain an session for this address from plugin */
2107   if (NULL == (papi = GST_plugins_find (address->transport_name)))
2108   {
2109     /* we don't have the plugin for this address */
2110     GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
2111     return;
2112   }
2113   if ((NULL == session) && (0 == address->address_length))
2114   {
2115     GNUNET_break (0);
2116     if (strlen (address->transport_name) > 0)
2117       GNUNET_ATS_address_destroyed (GST_ats, address, session);
2118     return;
2119   }
2120   if (NULL == session)
2121     session = papi->get_session (papi->cls, address);
2122   if (NULL == session)
2123   {
2124     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2125                 "Failed to obtain new session for peer `%s' and  address '%s'\n",
2126                 GNUNET_i2s (&address->peer), GST_plugins_a2s (address));    
2127     GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
2128     return;
2129   }
2130   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2131               "ATS tells us to switch to address '%s' for peer `%s'\n",
2132               (address->address_length != 0) ? GST_plugins_a2s (address): "<inbound>",
2133               GNUNET_i2s (peer));
2134   switch (n->state)
2135   {
2136   case S_NOT_CONNECTED:
2137     GNUNET_break (0);
2138     free_neighbour (n, GNUNET_NO);
2139     return;
2140   case S_INIT_ATS:
2141     set_address (&n->primary_address,
2142                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2143     n->state = S_INIT_BLACKLIST;
2144     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2145     check_blacklist (&n->id,
2146                      n->connect_ack_timestamp,
2147                      address, session, ats, ats_count);    
2148     break;
2149   case S_INIT_BLACKLIST:
2150     /* ATS suggests a different address, switch again */
2151     set_address (&n->primary_address,
2152                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2153     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2154     check_blacklist (&n->id,
2155                      n->connect_ack_timestamp,
2156                      address, session, ats, ats_count);    
2157     break;
2158   case S_CONNECT_SENT:
2159     /* ATS suggests a different address, switch again */
2160     set_address (&n->primary_address,
2161                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2162     n->state = S_INIT_BLACKLIST;
2163     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2164     check_blacklist (&n->id,
2165                      n->connect_ack_timestamp,
2166                      address, session, ats, ats_count);    
2167     break;
2168   case S_CONNECT_RECV_ATS:
2169     set_address (&n->primary_address,
2170                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2171     n->state = S_CONNECT_RECV_BLACKLIST;
2172     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2173     check_blacklist (&n->id,
2174                      n->connect_ack_timestamp,
2175                      address, session, ats, ats_count);    
2176     break;
2177   case S_CONNECT_RECV_BLACKLIST:
2178   case S_CONNECT_RECV_ACK:
2179     /* ATS asks us to switch while we were trying to connect; switch to new
2180        address and check blacklist again */
2181     set_address (&n->primary_address,
2182                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2183     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2184     check_blacklist (&n->id,
2185                      n->connect_ack_timestamp,
2186                      address, session, ats, ats_count);    
2187     break;
2188   case S_CONNECTED:
2189     GNUNET_assert (NULL != n->primary_address.address);
2190     GNUNET_assert (NULL != n->primary_address.session);
2191     if (n->primary_address.session == session)
2192     {
2193       /* not an address change, just a quota change */
2194       set_address (&n->primary_address,
2195                    address, session, bandwidth_in, bandwidth_out, GNUNET_YES);
2196       break;
2197     }
2198     /* ATS asks us to switch a life connection; see if we can get
2199        a CONNECT_ACK on it before we actually do this! */
2200     set_address (&n->alternative_address,
2201                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2202     n->state = S_CONNECTED_SWITCHING_BLACKLIST;
2203     check_blacklist (&n->id,
2204                      GNUNET_TIME_absolute_get (),
2205                      address, session, ats, ats_count);
2206     break;
2207   case S_RECONNECT_ATS:
2208     set_address (&n->primary_address,
2209                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2210     n->state = S_RECONNECT_BLACKLIST;
2211     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2212     check_blacklist (&n->id,
2213                      n->connect_ack_timestamp,
2214                      address, session, ats, ats_count);    
2215     break;
2216   case S_RECONNECT_BLACKLIST:
2217     /* ATS asks us to switch while we were trying to reconnect; switch to new
2218        address and check blacklist again */
2219     set_address (&n->primary_address,
2220                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2221     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2222     check_blacklist (&n->id,
2223                      n->connect_ack_timestamp,
2224                      address, session, ats, ats_count);    
2225     break;
2226   case S_RECONNECT_SENT:
2227     /* ATS asks us to switch while we were trying to reconnect; switch to new
2228        address and check blacklist again */
2229     set_address (&n->primary_address,
2230                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2231     n->state = S_RECONNECT_BLACKLIST;
2232     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2233     check_blacklist (&n->id,
2234                      n->connect_ack_timestamp,
2235                      address, session, ats, ats_count); 
2236     break;
2237   case S_CONNECTED_SWITCHING_BLACKLIST:
2238     if (n->primary_address.session == session)
2239     {
2240       /* ATS switches back to still-active session */
2241       free_address (&n->alternative_address);
2242       n->state = S_CONNECTED;
2243       break;
2244     }
2245     /* ATS asks us to switch a life connection, update blacklist check */
2246     set_address (&n->alternative_address,
2247                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2248     check_blacklist (&n->id,
2249                      GNUNET_TIME_absolute_get (),
2250                      address, session, ats, ats_count);
2251     break;
2252   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2253     if (n->primary_address.session == session)
2254     {
2255       /* ATS switches back to still-active session */
2256       free_address (&n->alternative_address);
2257       n->state = S_CONNECTED;
2258       break;
2259     }
2260     /* ATS asks us to switch a life connection, update blacklist check */
2261     set_address (&n->alternative_address,
2262                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2263     n->state = S_CONNECTED_SWITCHING_BLACKLIST;
2264     check_blacklist (&n->id,
2265                      GNUNET_TIME_absolute_get (),
2266                      address, session, ats, ats_count);
2267     break;
2268   case S_DISCONNECT:
2269     /* not going to switch addresses while disconnecting */
2270     return;
2271   case S_DISCONNECT_FINISHED:
2272     GNUNET_assert (0);
2273     break;
2274   default:
2275     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2276     GNUNET_break (0);
2277     break;
2278   }
2279 }
2280
2281
2282 /**
2283  * Master task run for every neighbour.  Performs all of the time-related
2284  * activities (keep alive, send next message, disconnect if idle, finish
2285  * clean up after disconnect).
2286  *
2287  * @param cls the 'struct NeighbourMapEntry' for which we are running
2288  * @param tc scheduler context (unused)
2289  */
2290 static void
2291 master_task (void *cls,
2292              const struct GNUNET_SCHEDULER_TaskContext *tc)
2293 {
2294   struct NeighbourMapEntry *n = cls;
2295   struct GNUNET_TIME_Relative delay;
2296
2297   n->task = GNUNET_SCHEDULER_NO_TASK;
2298   delay = GNUNET_TIME_absolute_get_remaining (n->timeout);  
2299   switch (n->state)
2300   {
2301   case S_NOT_CONNECTED:
2302     /* invalid state for master task, clean up */
2303     GNUNET_break (0);
2304     n->state = S_DISCONNECT_FINISHED;
2305     free_neighbour (n, GNUNET_NO);
2306     return;
2307   case S_INIT_ATS:
2308     if (0 == delay.rel_value)
2309     {
2310       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2311                   "Connection to `%s' timed out waiting for ATS to provide address\n",
2312                   GNUNET_i2s (&n->id));
2313       n->state = S_DISCONNECT_FINISHED;
2314       free_neighbour (n, GNUNET_NO);
2315       return;
2316     }
2317     break;
2318   case S_INIT_BLACKLIST:
2319     if (0 == delay.rel_value)
2320     {
2321       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2322                   "Connection to `%s' timed out waiting for BLACKLIST to approve address\n",
2323                   GNUNET_i2s (&n->id));
2324       n->state = S_DISCONNECT_FINISHED;
2325       free_neighbour (n, GNUNET_NO);
2326       return;
2327     }
2328     break;
2329   case S_CONNECT_SENT:
2330     if (0 == delay.rel_value)
2331     {
2332       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2333                   "Connection to `%s' timed out waiting for other peer to send CONNECT_ACK\n",
2334                   GNUNET_i2s (&n->id));
2335       disconnect_neighbour (n);
2336       return;
2337     }
2338     break;
2339   case S_CONNECT_RECV_ATS:
2340     if (0 == delay.rel_value)
2341     {
2342       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2343                   "Connection to `%s' timed out waiting ATS to provide address to use for CONNECT_ACK\n",
2344                   GNUNET_i2s (&n->id));
2345       n->state = S_DISCONNECT_FINISHED;
2346       free_neighbour (n, GNUNET_NO);
2347       return;
2348     }
2349     break;
2350   case S_CONNECT_RECV_BLACKLIST:
2351     if (0 == delay.rel_value)
2352     {
2353       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2354                   "Connection to `%s' timed out waiting BLACKLIST to approve address to use for CONNECT_ACK\n",
2355                   GNUNET_i2s (&n->id));
2356       n->state = S_DISCONNECT_FINISHED;
2357       free_neighbour (n, GNUNET_NO);
2358       return;
2359     }
2360     break;
2361   case S_CONNECT_RECV_ACK:
2362     if (0 == delay.rel_value)
2363     {
2364       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2365                   "Connection to `%s' timed out waiting for other peer to send SESSION_ACK\n",
2366                   GNUNET_i2s (&n->id));
2367       disconnect_neighbour (n);
2368       return;
2369     }
2370     break;
2371   case S_CONNECTED:
2372     if (0 == delay.rel_value)
2373     {
2374       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2375                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs\n",
2376                   GNUNET_i2s (&n->id));
2377       disconnect_neighbour (n);
2378       return;
2379     }
2380     try_transmission_to_peer (n);
2381     send_keepalive (n);
2382     break;
2383   case S_RECONNECT_ATS:
2384     if (0 == delay.rel_value)
2385     {
2386       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2387                   "Connection to `%s' timed out, waiting for ATS replacement address\n",
2388                   GNUNET_i2s (&n->id));
2389       disconnect_neighbour (n);
2390       return;
2391     }
2392     break;
2393   case S_RECONNECT_BLACKLIST:
2394     if (0 == delay.rel_value)
2395     {
2396       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2397                   "Connection to `%s' timed out, waiting for BLACKLIST to approve replacement address\n",
2398                   GNUNET_i2s (&n->id));
2399       disconnect_neighbour (n);
2400       return;
2401     }
2402     break;
2403   case S_RECONNECT_SENT:
2404     if (0 == delay.rel_value)
2405     {
2406       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2407                   "Connection to `%s' timed out, waiting for other peer to CONNECT_ACK replacement address\n",
2408                   GNUNET_i2s (&n->id));
2409       disconnect_neighbour (n);
2410       return;
2411     }
2412     break;
2413   case S_CONNECTED_SWITCHING_BLACKLIST:
2414     if (0 == delay.rel_value)
2415     {
2416       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2417                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs\n",
2418                   GNUNET_i2s (&n->id));
2419       disconnect_neighbour (n);
2420       return;
2421     }
2422     try_transmission_to_peer (n);
2423     send_keepalive (n);
2424     break;
2425   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2426     if (0 == delay.rel_value)
2427     {
2428       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2429                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs (after trying to CONNECT on alternative address)\n",
2430                   GNUNET_i2s (&n->id));
2431       disconnect_neighbour (n);
2432       return;
2433     }
2434     try_transmission_to_peer (n);
2435     send_keepalive (n);
2436     break;
2437   case S_DISCONNECT:
2438     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2439                 "Cleaning up connection to `%s' after sending DISCONNECT\n",
2440                 GNUNET_i2s (&n->id));
2441     n->state = S_DISCONNECT_FINISHED;
2442     free_neighbour (n, GNUNET_NO);
2443     return;
2444   case S_DISCONNECT_FINISHED:
2445     /* how did we get here!? */
2446     GNUNET_assert (0);
2447     break;
2448   default:
2449     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2450     GNUNET_break (0);
2451     break;  
2452   }
2453   delay = GNUNET_TIME_relative_min (GNUNET_TIME_absolute_get_remaining (n->keep_alive_time),
2454                                     delay);
2455   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == n->task);
2456   n->task = GNUNET_SCHEDULER_add_delayed (delay,
2457                                           &master_task,
2458                                           n);
2459 }
2460
2461
2462 /**
2463  * Send a SESSION_ACK message to the neighbour to confirm that we
2464  * got his CONNECT_ACK.
2465  *
2466  * @param n neighbour to send the SESSION_ACK to
2467  */
2468 static void
2469 send_session_ack_message (struct NeighbourMapEntry *n)
2470 {
2471   struct GNUNET_MessageHeader msg;
2472
2473   msg.size = htons (sizeof (struct GNUNET_MessageHeader));
2474   msg.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_ACK);
2475   (void) send_with_session(n,
2476                            (const char *) &msg, sizeof (struct GNUNET_MessageHeader),
2477                            UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_REL,
2478                            NULL, NULL);
2479 }
2480
2481
2482 /**
2483  * We received a 'SESSION_CONNECT_ACK' message from the other peer.
2484  * Consider switching to it.
2485  *
2486  * @param message possibly a 'struct SessionConnectMessage' (check format)
2487  * @param peer identity of the peer to switch the address for
2488  * @param address address of the other peer, NULL if other peer
2489  *                       connected to us
2490  * @param session session to use (or NULL)
2491  * @param ats performance data
2492  * @param ats_count number of entries in ats
2493  */
2494 void
2495 GST_neighbours_handle_connect_ack (const struct GNUNET_MessageHeader *message,
2496                                    const struct GNUNET_PeerIdentity *peer,
2497                                    const struct GNUNET_HELLO_Address *address,
2498                                    struct Session *session,
2499                                    const struct GNUNET_ATS_Information *ats,
2500                                    uint32_t ats_count)
2501 {
2502   const struct SessionConnectMessage *scm;
2503   struct GNUNET_TIME_Absolute ts;
2504   struct NeighbourMapEntry *n;
2505
2506   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2507               "Received CONNECT_ACK message from peer `%s'\n",
2508               GNUNET_i2s (peer));
2509   if (ntohs (message->size) != sizeof (struct SessionConnectMessage))
2510   {
2511     GNUNET_break_op (0);
2512     return;
2513   }
2514   scm = (const struct SessionConnectMessage *) message;
2515   GNUNET_break_op (ntohl (scm->reserved) == 0);
2516   if (NULL == (n = lookup_neighbour (peer)))
2517   {
2518     GNUNET_STATISTICS_update (GST_stats,
2519                               gettext_noop
2520                               ("# unexpected CONNECT_ACK messages (no peer)"),
2521                               1, GNUNET_NO);
2522     return;
2523   }
2524   ts = GNUNET_TIME_absolute_ntoh (scm->timestamp);
2525   switch (n->state)
2526   {
2527   case S_NOT_CONNECTED:
2528     GNUNET_break (0);
2529     free_neighbour (n, GNUNET_NO);
2530     return;
2531   case S_INIT_ATS:
2532   case S_INIT_BLACKLIST:
2533     GNUNET_STATISTICS_update (GST_stats,
2534                               gettext_noop
2535                               ("# unexpected CONNECT_ACK messages (not ready)"),
2536                               1, GNUNET_NO);
2537     break;    
2538   case S_CONNECT_SENT:
2539     if (ts.abs_value != n->primary_address.connect_timestamp.abs_value)
2540       break; /* ACK does not match our original CONNECT message */
2541     n->state = S_CONNECTED;
2542     n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2543     GNUNET_STATISTICS_set (GST_stats, 
2544                            gettext_noop ("# peers connected"), 
2545                            ++neighbours_connected,
2546                            GNUNET_NO);
2547     connect_notify_cb (callback_cls, &n->id, ats, ats_count);
2548     set_address (&n->primary_address,
2549                  n->primary_address.address,
2550                  n->primary_address.session,
2551                  n->primary_address.bandwidth_in,
2552                  n->primary_address.bandwidth_out,
2553                  GNUNET_YES);
2554     send_session_ack_message (n);
2555     break;
2556   case S_CONNECT_RECV_ATS:
2557   case S_CONNECT_RECV_BLACKLIST:
2558   case S_CONNECT_RECV_ACK:
2559     GNUNET_STATISTICS_update (GST_stats,
2560                               gettext_noop
2561                               ("# unexpected CONNECT_ACK messages (not ready)"),
2562                               1, GNUNET_NO);
2563     break;
2564   case S_CONNECTED:
2565     /* duplicate CONNECT_ACK, let's answer by duplciate SESSION_ACK just in case */
2566     send_session_ack_message (n);
2567     break;
2568   case S_RECONNECT_ATS:
2569   case S_RECONNECT_BLACKLIST:
2570     /* we didn't expect any CONNECT_ACK, as we are waiting for ATS
2571        to give us a new address... */
2572     GNUNET_STATISTICS_update (GST_stats,
2573                               gettext_noop
2574                               ("# unexpected CONNECT_ACK messages (waiting on ATS)"),
2575                               1, GNUNET_NO);
2576     break;
2577   case S_RECONNECT_SENT:
2578     /* new address worked; go back to connected! */
2579     n->state = S_CONNECTED;
2580     send_session_ack_message (n);
2581     break;
2582   case S_CONNECTED_SWITCHING_BLACKLIST:
2583     /* duplicate CONNECT_ACK, let's answer by duplciate SESSION_ACK just in case */
2584     send_session_ack_message (n);
2585     break;
2586   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2587     /* new address worked; adopt it and go back to connected! */
2588     n->state = S_CONNECTED;
2589     n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2590     GNUNET_break (GNUNET_NO == n->alternative_address.ats_active);
2591     set_address (&n->primary_address,
2592                  n->alternative_address.address,
2593                  n->alternative_address.session,
2594                  n->alternative_address.bandwidth_in,
2595                  n->alternative_address.bandwidth_out,
2596                  GNUNET_YES);
2597     free_address (&n->alternative_address);
2598     send_session_ack_message (n);
2599     break;    
2600   case S_DISCONNECT:
2601     GNUNET_STATISTICS_update (GST_stats,
2602                               gettext_noop
2603                               ("# unexpected CONNECT_ACK messages (disconnecting)"),
2604                               1, GNUNET_NO);
2605     break;
2606   case S_DISCONNECT_FINISHED:
2607     GNUNET_assert (0);
2608     break;
2609   default:
2610     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2611     GNUNET_break (0);
2612     break;   
2613   }
2614 }
2615
2616
2617 /**
2618  * A session was terminated. Take note; if needed, try to get
2619  * an alternative address from ATS.
2620  *
2621  * @param peer identity of the peer where the session died
2622  * @param session session that is gone
2623  */
2624 void
2625 GST_neighbours_session_terminated (const struct GNUNET_PeerIdentity *peer,
2626                                    struct Session *session)
2627 {
2628   struct NeighbourMapEntry *n;
2629   struct BlackListCheckContext *bcc;
2630   struct BlackListCheckContext *bcc_next;
2631
2632   /* make sure to cancel all ongoing blacklist checks involving 'session' */
2633   bcc_next = bc_head;
2634   while (NULL != (bcc = bcc_next))
2635   {
2636     bcc_next = bcc->next;
2637     if (bcc->na.session == session)
2638     {
2639       GST_blacklist_test_cancel (bcc->bc);
2640       GNUNET_HELLO_address_free (bcc->na.address);
2641       GNUNET_CONTAINER_DLL_remove (bc_head,
2642                                    bc_tail,
2643                                    bcc);
2644       GNUNET_free (bcc);
2645     }
2646   }
2647   if (NULL == (n = lookup_neighbour (peer)))
2648     return; /* can't affect us */
2649   if (session != n->primary_address.session)
2650   {
2651     if (session == n->alternative_address.session)
2652     {
2653       free_address (&n->alternative_address);
2654       if ( (S_CONNECTED_SWITCHING_BLACKLIST == n->state) ||
2655            (S_CONNECTED_SWITCHING_CONNECT_SENT == n->state) )
2656         n->state = S_CONNECTED;
2657       else
2658         GNUNET_break (0);
2659     }
2660     return; /* doesn't affect us further */
2661   }
2662
2663   n->expect_latency_response = GNUNET_NO;
2664
2665   switch (n->state)
2666   {
2667   case S_NOT_CONNECTED:
2668     GNUNET_break (0);
2669     free_neighbour (n, GNUNET_NO);
2670     return;
2671   case S_INIT_ATS:
2672     GNUNET_break (0);
2673     free_neighbour (n, GNUNET_NO);
2674     return;
2675   case S_INIT_BLACKLIST:
2676   case S_CONNECT_SENT:
2677     free_address (&n->primary_address);
2678     n->state = S_INIT_ATS;
2679     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
2680     // FIXME: need to ask ATS for suggestions again?
2681     GNUNET_ATS_suggest_address (GST_ats, &n->id);
2682     break;
2683   case S_CONNECT_RECV_ATS:    
2684   case S_CONNECT_RECV_BLACKLIST:
2685   case S_CONNECT_RECV_ACK:
2686     /* error on inbound session; free neighbour entirely */
2687     free_address (&n->primary_address);
2688     free_neighbour (n, GNUNET_NO);
2689     return;
2690   case S_CONNECTED:
2691     free_address (&n->primary_address);
2692     n->state = S_RECONNECT_ATS;
2693     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
2694     /* FIXME: is this ATS call needed? */
2695     GNUNET_ATS_suggest_address (GST_ats, &n->id);
2696     break;
2697   case S_RECONNECT_ATS:
2698     /* we don't have an address, how can it go down? */
2699     GNUNET_break (0);
2700     break;
2701   case S_RECONNECT_BLACKLIST:
2702   case S_RECONNECT_SENT:
2703     n->state = S_RECONNECT_ATS;
2704     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
2705     // FIXME: need to ask ATS for suggestions again?
2706     GNUNET_ATS_suggest_address (GST_ats, &n->id);
2707     break;
2708   case S_CONNECTED_SWITCHING_BLACKLIST:
2709     /* primary went down while we were checking secondary against
2710        blacklist, adopt secondary as primary */       
2711     free_address (&n->primary_address);
2712     n->primary_address = n->alternative_address;
2713     memset (&n->alternative_address, 0, sizeof (struct NeighbourAddress));
2714     n->timeout = GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT);
2715     n->state = S_RECONNECT_BLACKLIST;
2716     break;
2717   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2718     /* primary went down while we were waiting for CONNECT_ACK on secondary;
2719        secondary as primary */       
2720     free_address (&n->primary_address);
2721     n->primary_address = n->alternative_address;
2722     memset (&n->alternative_address, 0, sizeof (struct NeighbourAddress));
2723     n->timeout = GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT);
2724     n->state = S_RECONNECT_SENT;
2725     break;
2726   case S_DISCONNECT:
2727     free_address (&n->primary_address);
2728     break;
2729   case S_DISCONNECT_FINISHED:
2730     /* neighbour was freed and plugins told to terminate session */
2731     break;
2732   default:
2733     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2734     GNUNET_break (0);
2735     break;
2736   }
2737   if (GNUNET_SCHEDULER_NO_TASK != n->task)
2738     GNUNET_SCHEDULER_cancel (n->task);
2739   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
2740 }
2741
2742
2743 /**
2744  * We received a 'SESSION_ACK' message from the other peer.
2745  * If we sent a 'CONNECT_ACK' last, this means we are now
2746  * connected.  Otherwise, do nothing.
2747  *
2748  * @param message possibly a 'struct SessionConnectMessage' (check format)
2749  * @param peer identity of the peer to switch the address for
2750  * @param address address of the other peer, NULL if other peer
2751  *                       connected to us
2752  * @param session session to use (or NULL)
2753  * @param ats performance data
2754  * @param ats_count number of entries in ats
2755  */
2756 void
2757 GST_neighbours_handle_session_ack (const struct GNUNET_MessageHeader *message,
2758                                    const struct GNUNET_PeerIdentity *peer,
2759                                    const struct GNUNET_HELLO_Address *address,
2760                                    struct Session *session,
2761                                    const struct GNUNET_ATS_Information *ats,
2762                                    uint32_t ats_count)
2763 {
2764   struct NeighbourMapEntry *n;
2765
2766   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
2767               "Received SESSION_ACK message from peer `%s'\n",
2768               GNUNET_i2s (peer));
2769   if (ntohs (message->size) != sizeof (struct GNUNET_MessageHeader))
2770   {
2771     GNUNET_break_op (0);
2772     return;
2773   }
2774   if (NULL == (n = lookup_neighbour (peer)))
2775     return;
2776   /* check if we are in a plausible state for having sent
2777      a CONNECT_ACK.  If not, return, otherwise break */
2778   if ( ( (S_CONNECT_RECV_ACK != n->state) &&
2779          (S_CONNECT_SENT != n->state) ) ||
2780        (2 != n->send_connect_ack) )
2781   {
2782     GNUNET_STATISTICS_update (GST_stats,
2783                               gettext_noop ("# unexpected SESSION ACK messages"), 1,
2784                               GNUNET_NO);
2785     return;
2786   }
2787   n->state = S_CONNECTED;
2788   n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2789   GNUNET_STATISTICS_set (GST_stats, 
2790                          gettext_noop ("# peers connected"), 
2791                          ++neighbours_connected,
2792                          GNUNET_NO);
2793   connect_notify_cb (callback_cls, &n->id, ats, ats_count);
2794   set_address (&n->primary_address,
2795                n->primary_address.address,
2796                n->primary_address.session,
2797                n->primary_address.bandwidth_in,
2798                n->primary_address.bandwidth_out,
2799                GNUNET_YES);
2800 }
2801
2802
2803 /**
2804  * Test if we're connected to the given peer.
2805  *
2806  * @param target peer to test
2807  * @return GNUNET_YES if we are connected, GNUNET_NO if not
2808  */
2809 int
2810 GST_neighbours_test_connected (const struct GNUNET_PeerIdentity *target)
2811 {
2812   return test_connected (lookup_neighbour (target));
2813 }
2814
2815
2816 /**
2817  * Change the incoming quota for the given peer.
2818  *
2819  * @param neighbour identity of peer to change qutoa for
2820  * @param quota new quota
2821  */
2822 void
2823 GST_neighbours_set_incoming_quota (const struct GNUNET_PeerIdentity *neighbour,
2824                                    struct GNUNET_BANDWIDTH_Value32NBO quota)
2825 {
2826   struct NeighbourMapEntry *n;
2827
2828   if (NULL == (n = lookup_neighbour (neighbour)))
2829   {
2830     GNUNET_STATISTICS_update (GST_stats,
2831                               gettext_noop
2832                               ("# SET QUOTA messages ignored (no such peer)"),
2833                               1, GNUNET_NO);
2834     return;
2835   }
2836   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2837               "Setting inbound quota of %u Bps for peer `%s' to all clients\n",
2838               ntohl (quota.value__), GNUNET_i2s (&n->id));
2839   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker, quota);
2840   if (0 != ntohl (quota.value__))
2841     return;
2842   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting peer `%4s' due to `%s'\n",
2843               GNUNET_i2s (&n->id), "SET_QUOTA");
2844   if (GNUNET_YES == test_connected (n))
2845     GNUNET_STATISTICS_update (GST_stats,
2846                               gettext_noop ("# disconnects due to quota of 0"),
2847                               1, GNUNET_NO);
2848   disconnect_neighbour (n);
2849 }
2850
2851
2852 /**
2853  * We received a disconnect message from the given peer,
2854  * validate and process.
2855  *
2856  * @param peer sender of the message
2857  * @param msg the disconnect message
2858  */
2859 void
2860 GST_neighbours_handle_disconnect_message (const struct GNUNET_PeerIdentity
2861                                           *peer,
2862                                           const struct GNUNET_MessageHeader
2863                                           *msg)
2864 {
2865   struct NeighbourMapEntry *n;
2866   const struct SessionDisconnectMessage *sdm;
2867   GNUNET_HashCode hc;
2868
2869   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2870               "Received DISCONNECT message from peer `%s'\n",
2871               GNUNET_i2s (peer));
2872   if (ntohs (msg->size) != sizeof (struct SessionDisconnectMessage))
2873   {
2874     // GNUNET_break_op (0);
2875     GNUNET_STATISTICS_update (GST_stats,
2876                               gettext_noop
2877                               ("# disconnect messages ignored (old format)"), 1,
2878                               GNUNET_NO);
2879     return;
2880   }
2881   sdm = (const struct SessionDisconnectMessage *) msg;
2882   if (NULL == (n = lookup_neighbour (peer)))
2883     return;                     /* gone already */
2884   if (GNUNET_TIME_absolute_ntoh (sdm->timestamp).abs_value <= n->connect_ack_timestamp.abs_value)
2885   {
2886     GNUNET_STATISTICS_update (GST_stats,
2887                               gettext_noop
2888                               ("# disconnect messages ignored (timestamp)"), 1,
2889                               GNUNET_NO);
2890     return;
2891   }
2892   GNUNET_CRYPTO_hash (&sdm->public_key,
2893                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2894                       &hc);
2895   if (0 != memcmp (peer, &hc, sizeof (struct GNUNET_PeerIdentity)))
2896   {
2897     GNUNET_break_op (0);
2898     return;
2899   }
2900   if (ntohl (sdm->purpose.size) !=
2901       sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2902       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
2903       sizeof (struct GNUNET_TIME_AbsoluteNBO))
2904   {
2905     GNUNET_break_op (0);
2906     return;
2907   }
2908   if (GNUNET_OK !=
2909       GNUNET_CRYPTO_rsa_verify
2910       (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT, &sdm->purpose,
2911        &sdm->signature, &sdm->public_key))
2912   {
2913     GNUNET_break_op (0);
2914     return;
2915   }
2916   if (GNUNET_YES == test_connected (n))
2917     GNUNET_STATISTICS_update (GST_stats,
2918                               gettext_noop
2919                               ("# other peer asked to disconnect from us"), 1,
2920                               GNUNET_NO);
2921   disconnect_neighbour (n);
2922 }
2923
2924
2925 /**
2926  * Closure for the neighbours_iterate function.
2927  */
2928 struct IteratorContext
2929 {
2930   /**
2931    * Function to call on each connected neighbour.
2932    */
2933   GST_NeighbourIterator cb;
2934
2935   /**
2936    * Closure for 'cb'.
2937    */
2938   void *cb_cls;
2939 };
2940
2941
2942 /**
2943  * Call the callback from the closure for each connected neighbour.
2944  *
2945  * @param cls the 'struct IteratorContext'
2946  * @param key the hash of the public key of the neighbour
2947  * @param value the 'struct NeighbourMapEntry'
2948  * @return GNUNET_OK (continue to iterate)
2949  */
2950 static int
2951 neighbours_iterate (void *cls, const GNUNET_HashCode * key, void *value)
2952 {
2953   struct IteratorContext *ic = cls;
2954   struct NeighbourMapEntry *n = value;
2955
2956   if (GNUNET_YES == test_connected (n))
2957     ic->cb (ic->cb_cls, &n->id, NULL, 0, n->primary_address.address);
2958   return GNUNET_OK;
2959 }
2960
2961
2962 /**
2963  * Iterate over all connected neighbours.
2964  *
2965  * @param cb function to call
2966  * @param cb_cls closure for cb
2967  */
2968 void
2969 GST_neighbours_iterate (GST_NeighbourIterator cb, void *cb_cls)
2970 {
2971   struct IteratorContext ic;
2972
2973   if (NULL == neighbours)  
2974     return; /* can happen during shutdown */
2975   ic.cb = cb;
2976   ic.cb_cls = cb_cls;
2977   GNUNET_CONTAINER_multihashmap_iterate (neighbours, &neighbours_iterate, &ic);
2978 }
2979
2980
2981 /**
2982  * If we have an active connection to the given target, it must be shutdown.
2983  *
2984  * @param target peer to disconnect from
2985  */
2986 void
2987 GST_neighbours_force_disconnect (const struct GNUNET_PeerIdentity *target)
2988 {
2989   struct NeighbourMapEntry *n;
2990
2991   if (NULL == (n = lookup_neighbour (target)))
2992     return;  /* not active */
2993   if (GNUNET_YES == test_connected (n))
2994     GNUNET_STATISTICS_update (GST_stats,
2995                               gettext_noop
2996                               ("# disconnected from peer upon explicit request"), 1,
2997                               GNUNET_NO);
2998   disconnect_neighbour (n);
2999 }
3000
3001
3002 /**
3003  * Obtain current latency information for the given neighbour.
3004  *
3005  * @param peer to get the latency for
3006  * @return observed latency of the address, FOREVER if the 
3007  *         the connection is not up
3008  */
3009 struct GNUNET_TIME_Relative
3010 GST_neighbour_get_latency (const struct GNUNET_PeerIdentity *peer)
3011 {
3012   struct NeighbourMapEntry *n;
3013
3014   n = lookup_neighbour (peer);
3015   if (NULL == n) 
3016     return GNUNET_TIME_UNIT_FOREVER_REL;
3017   switch (n->state)
3018   {
3019   case S_CONNECTED:
3020   case S_RECONNECT_SENT:
3021   case S_RECONNECT_ATS:
3022     return n->latency;
3023   case S_NOT_CONNECTED:
3024   case S_INIT_BLACKLIST:
3025   case S_INIT_ATS:
3026   case S_CONNECT_SENT:
3027   case S_CONNECT_RECV_BLACKLIST:
3028   case S_DISCONNECT:
3029   case S_DISCONNECT_FINISHED:
3030     return GNUNET_TIME_UNIT_FOREVER_REL;
3031   default:
3032     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
3033     GNUNET_break (0);
3034     break;
3035   }
3036   return GNUNET_TIME_UNIT_FOREVER_REL;   
3037 }
3038
3039
3040 /**
3041  * Obtain current address information for the given neighbour.
3042  *
3043  * @param peer
3044  * @return address currently used
3045  */
3046 struct GNUNET_HELLO_Address *
3047 GST_neighbour_get_current_address (const struct GNUNET_PeerIdentity *peer)
3048 {
3049   struct NeighbourMapEntry *n;
3050
3051   n = lookup_neighbour (peer);
3052   if (NULL == n)
3053     return NULL;
3054   return n->primary_address.address;
3055 }
3056
3057
3058 /**
3059  * Initialize the neighbours subsystem.
3060  *
3061  * @param cls closure for callbacks
3062  * @param connect_cb function to call if we connect to a peer
3063  * @param disconnect_cb function to call if we disconnect from a peer
3064  * @param peer_address_cb function to call if we change an active address
3065  *                   of a neighbour
3066  */
3067 void
3068 GST_neighbours_start (void *cls,
3069                       GNUNET_TRANSPORT_NotifyConnect connect_cb,
3070                       GNUNET_TRANSPORT_NotifyDisconnect disconnect_cb,
3071                       GNUNET_TRANSPORT_PeerIterateCallback peer_address_cb)
3072 {
3073   callback_cls = cls;
3074   connect_notify_cb = connect_cb;
3075   disconnect_notify_cb = disconnect_cb;
3076   address_change_cb = peer_address_cb;
3077   neighbours = GNUNET_CONTAINER_multihashmap_create (NEIGHBOUR_TABLE_SIZE);
3078 }
3079
3080
3081 /**
3082  * Disconnect from the given neighbour.
3083  *
3084  * @param cls unused
3085  * @param key hash of neighbour's public key (not used)
3086  * @param value the 'struct NeighbourMapEntry' of the neighbour
3087  * @return GNUNET_OK (continue to iterate)
3088  */
3089 static int
3090 disconnect_all_neighbours (void *cls, const GNUNET_HashCode * key, void *value)
3091 {
3092   struct NeighbourMapEntry *n = value;
3093
3094   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
3095               "Disconnecting peer `%4s', %s\n",
3096               GNUNET_i2s (&n->id), "SHUTDOWN_TASK");
3097   n->state = S_DISCONNECT_FINISHED;
3098   free_neighbour (n, GNUNET_NO);
3099   return GNUNET_OK;
3100 }
3101
3102
3103 /**
3104  * Cleanup the neighbours subsystem.
3105  */
3106 void
3107 GST_neighbours_stop ()
3108 {
3109   if (NULL == neighbours)
3110     return;
3111   GNUNET_CONTAINER_multihashmap_iterate (neighbours, 
3112                                          &disconnect_all_neighbours,
3113                                          NULL);
3114   GNUNET_CONTAINER_multihashmap_destroy (neighbours);
3115   neighbours = NULL;
3116   callback_cls = NULL;
3117   connect_notify_cb = NULL;
3118   disconnect_notify_cb = NULL;
3119   address_change_cb = NULL;
3120 }
3121
3122
3123 /* end of file gnunet-service-transport_neighbours.c */