-fix kill logic (#2381), interpretation of flag was inverted
[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 keep_sessions GNUNET_NO to tell plugin to terminate sessions,
851  *                      GNUNET_YES to keep all sessions
852  */
853 static void
854 free_neighbour (struct NeighbourMapEntry *n, int keep_sessions)
855 {
856   struct MessageQueue *mq;
857   struct GNUNET_TRANSPORT_PluginFunctions *papi;
858
859   n->is_active = NULL; /* always free'd by its own continuation! */
860
861   /* fail messages currently in the queue */
862   while (NULL != (mq = n->messages_head))
863   {
864     GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
865     if (NULL != mq->cont)
866       mq->cont (mq->cont_cls, GNUNET_SYSERR);
867     GNUNET_free (mq);
868   }
869   /* It is too late to send other peer disconnect notifications, but at
870      least internally we need to get clean... */
871   if (GNUNET_YES == test_connected (n))
872   {
873     GNUNET_STATISTICS_set (GST_stats, 
874                            gettext_noop ("# peers connected"), 
875                            --neighbours_connected,
876                            GNUNET_NO);
877     disconnect_notify_cb (callback_cls, &n->id);
878   }
879
880   /* FIXME-PLUGIN-API: This does not seem to guarantee that all
881      transport sessions eventually get killed due to inactivity; they
882      MUST have their own timeout logic (but at least TCP doesn't have
883      one yet).  Are we sure that EVERY 'session' of a plugin is
884      actually cleaned up this way!?  Note that if we are switching
885      between two TCP sessions to the same peer, the existing plugin
886      API gives us not even the means to selectively kill only one of
887      them! Killing all sessions like this seems to be very, very
888      wrong. */
889   if ((GNUNET_NO == keep_sessions) &&
890       (NULL != n->primary_address.address) &&
891       (NULL != (papi = GST_plugins_find (n->primary_address.address->transport_name))))
892     papi->disconnect (papi->cls, &n->id);
893
894   n->state = S_DISCONNECT_FINISHED;
895
896   GNUNET_assert (GNUNET_YES ==
897                  GNUNET_CONTAINER_multihashmap_remove (neighbours,
898                                                        &n->id.hashPubKey, n));
899
900   /* cut transport-level connection */
901   free_address (&n->primary_address);
902   free_address (&n->alternative_address);
903
904   // FIXME-ATS-API: we might want to be more specific about
905   // which states we do this from in the future (ATS should
906   // have given us a 'suggest_address' handle, and if we have
907   // such a handle, we should cancel the operation here!
908   GNUNET_ATS_suggest_address_cancel (GST_ats, &n->id);
909
910   if (GNUNET_SCHEDULER_NO_TASK != n->task)
911   {
912     GNUNET_SCHEDULER_cancel (n->task);
913     n->task = GNUNET_SCHEDULER_NO_TASK;
914   }
915   /* free rest of memory */
916   GNUNET_free (n);
917 }
918
919
920 /**
921  * Transmit a message using the current session of the given
922  * neighbour.
923  *
924  * @param n entry for the recipient
925  * @param msgbuf buffer to transmit
926  * @param msgbuf_size number of bytes in buffer
927  * @param priority transmission priority
928  * @param timeout transmission timeout
929  * @param cont continuation to call when finished (can be NULL)
930  * @param cont_cls closure for cont
931  */
932 static void
933 send_with_session (struct NeighbourMapEntry *n,
934                    const char *msgbuf, size_t msgbuf_size,
935                    uint32_t priority,
936                    struct GNUNET_TIME_Relative timeout,
937                    GNUNET_TRANSPORT_TransmitContinuation cont,
938                    void *cont_cls)
939 {
940   struct GNUNET_TRANSPORT_PluginFunctions *papi;
941
942   GNUNET_assert (n->primary_address.session != NULL);
943   if ( ( (NULL == (papi = GST_plugins_find (n->primary_address.address->transport_name))) ||
944          (-1 == papi->send (papi->cls,
945                             n->primary_address.session,
946                             msgbuf, msgbuf_size,
947                             priority,
948                             timeout,
949                             cont, cont_cls))) &&
950        (NULL != cont) )
951     cont (cont_cls, &n->id, GNUNET_SYSERR);
952   GNUNET_break (NULL != papi);
953 }
954
955
956 /**
957  * Master task run for every neighbour.  Performs all of the time-related
958  * activities (keep alive, send next message, disconnect if idle, finish
959  * clean up after disconnect).
960  *
961  * @param cls the 'struct NeighbourMapEntry' for which we are running
962  * @param tc scheduler context (unused)
963  */
964 static void
965 master_task (void *cls,
966              const struct GNUNET_SCHEDULER_TaskContext *tc);
967
968
969 /**
970  * Function called when the 'DISCONNECT' message has been sent by the
971  * plugin.  Frees the neighbour --- if the entry still exists.
972  *
973  * @param cls NULL
974  * @param target identity of the neighbour that was disconnected
975  * @param result GNUNET_OK if the disconnect got out successfully
976  */
977 static void
978 send_disconnect_cont (void *cls, const struct GNUNET_PeerIdentity *target,
979                       int result)
980 {
981   struct NeighbourMapEntry *n;
982
983   n = lookup_neighbour (target);
984   if (NULL == n)
985     return; /* already gone */
986   if (S_DISCONNECT != n->state)
987     return; /* have created a fresh entry since */
988   n->state = S_DISCONNECT;
989   GNUNET_SCHEDULER_cancel (n->task);
990   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
991 }
992
993
994 /**
995  * Transmit a DISCONNECT message to the other peer.
996  *
997  * @param n neighbour to send DISCONNECT message.
998  */
999 static void
1000 send_disconnect (struct NeighbourMapEntry *n)
1001 {
1002   struct SessionDisconnectMessage disconnect_msg;
1003
1004   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1005               "Sending DISCONNECT message to peer `%4s'\n",
1006               GNUNET_i2s (&n->id));
1007   disconnect_msg.header.size = htons (sizeof (struct SessionDisconnectMessage));
1008   disconnect_msg.header.type =
1009       htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT);
1010   disconnect_msg.reserved = htonl (0);
1011   disconnect_msg.purpose.size =
1012       htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
1013              sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
1014              sizeof (struct GNUNET_TIME_AbsoluteNBO));
1015   disconnect_msg.purpose.purpose =
1016       htonl (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT);
1017   disconnect_msg.timestamp =
1018       GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
1019   disconnect_msg.public_key = GST_my_public_key;
1020   GNUNET_assert (GNUNET_OK ==
1021                  GNUNET_CRYPTO_rsa_sign (GST_my_private_key,
1022                                          &disconnect_msg.purpose,
1023                                          &disconnect_msg.signature));
1024
1025   send_with_session (n,
1026                      (const char *) &disconnect_msg, sizeof (disconnect_msg),
1027                      UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_REL,
1028                      &send_disconnect_cont, NULL);
1029   GNUNET_STATISTICS_update (GST_stats,
1030                             gettext_noop
1031                             ("# DISCONNECT messages sent"), 1,
1032                             GNUNET_NO);
1033 }
1034
1035
1036 /**
1037  * Disconnect from the given neighbour, clean up the record.
1038  *
1039  * @param n neighbour to disconnect from
1040  */
1041 static void
1042 disconnect_neighbour (struct NeighbourMapEntry *n)
1043 {
1044   /* depending on state, notify neighbour and/or upper layers of this peer 
1045      about disconnect */
1046   switch (n->state)
1047   {
1048   case S_NOT_CONNECTED:
1049   case S_INIT_ATS:
1050   case S_INIT_BLACKLIST:
1051     /* other peer is completely unaware of us, no need to send DISCONNECT */
1052     n->state = S_DISCONNECT_FINISHED;
1053     free_neighbour (n, GNUNET_NO);
1054     return;
1055   case S_CONNECT_SENT:
1056     send_disconnect (n); 
1057     n->state = S_DISCONNECT;
1058     break;   
1059   case S_CONNECT_RECV_ATS:
1060   case S_CONNECT_RECV_BLACKLIST:
1061     /* we never ACK'ed the other peer's request, no need to send DISCONNECT */
1062     n->state = S_DISCONNECT_FINISHED;
1063     free_neighbour (n, GNUNET_NO);
1064     return;
1065   case S_CONNECT_RECV_ACK:
1066     /* we DID ACK the other peer's request, must send DISCONNECT */
1067     send_disconnect (n); 
1068     n->state = S_DISCONNECT;
1069     break;   
1070   case S_CONNECTED:
1071   case S_RECONNECT_BLACKLIST:
1072   case S_RECONNECT_SENT:
1073   case S_CONNECTED_SWITCHING_BLACKLIST:
1074   case S_CONNECTED_SWITCHING_CONNECT_SENT:
1075     /* we are currently connected, need to send disconnect and do
1076        internal notifications and update statistics */
1077     send_disconnect (n);
1078     GNUNET_STATISTICS_set (GST_stats, 
1079                            gettext_noop ("# peers connected"), 
1080                            --neighbours_connected,
1081                            GNUNET_NO);
1082     disconnect_notify_cb (callback_cls, &n->id);
1083     n->state = S_DISCONNECT;
1084     break;
1085   case S_RECONNECT_ATS:
1086     /* ATS address request timeout, disconnect without sending disconnect message */
1087     GNUNET_STATISTICS_set (GST_stats,
1088                            gettext_noop ("# peers connected"),
1089                            --neighbours_connected,
1090                            GNUNET_NO);
1091     disconnect_notify_cb (callback_cls, &n->id);
1092     n->state = S_DISCONNECT;
1093     break;
1094   case S_DISCONNECT:
1095     /* already disconnected, ignore */
1096     break;
1097   case S_DISCONNECT_FINISHED:
1098     /* already cleaned up, how did we get here!? */
1099     GNUNET_assert (0);
1100     break;
1101   default:
1102     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
1103     GNUNET_break (0);
1104     break;
1105   }
1106   /* schedule timeout to clean up */
1107   if (GNUNET_SCHEDULER_NO_TASK != n->task)
1108     GNUNET_SCHEDULER_cancel (n->task);
1109   n->task = GNUNET_SCHEDULER_add_delayed (DISCONNECT_SENT_TIMEOUT,
1110                                           &master_task, n);
1111 }
1112
1113
1114 /**
1115  * We're done with our transmission attempt, continue processing.
1116  *
1117  * @param cls the 'struct MessageQueue' of the message
1118  * @param receiver intended receiver
1119  * @param success whether it worked or not
1120  */
1121 static void
1122 transmit_send_continuation (void *cls,
1123                             const struct GNUNET_PeerIdentity *receiver,
1124                             int success)
1125 {
1126   struct MessageQueue *mq = cls;
1127   struct NeighbourMapEntry *n;
1128
1129   if (NULL == (n = lookup_neighbour (receiver)))
1130     return; /* disconnect or other error while transmitting, can happen */
1131   if (n->is_active == mq)
1132   {
1133     /* this is still "our" neighbour, remove us from its queue
1134        and allow it to send the next message now */
1135     n->is_active = NULL;
1136     GNUNET_SCHEDULER_cancel (n->task);
1137     n->task = GNUNET_SCHEDULER_add_now (&master_task, n);    
1138   }
1139   GNUNET_assert (bytes_in_send_queue >= mq->message_buf_size);
1140   bytes_in_send_queue -= mq->message_buf_size;
1141   GNUNET_STATISTICS_set (GST_stats,
1142                         gettext_noop
1143                          ("# bytes in message queue for other peers"),
1144                          bytes_in_send_queue, GNUNET_NO);
1145   if (GNUNET_OK == success)
1146     GNUNET_STATISTICS_update (GST_stats,
1147                               gettext_noop
1148                               ("# messages transmitted to other peers"),
1149                               1, GNUNET_NO);
1150   else
1151     GNUNET_STATISTICS_update (GST_stats,
1152                               gettext_noop
1153                               ("# transmission failures for messages to other peers"),
1154                               1, GNUNET_NO);
1155   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1156               "Sending message to `%s' of type %u was a %s\n",
1157               GNUNET_i2s (receiver),
1158               ntohs (((struct GNUNET_MessageHeader *) mq->message_buf)->type),
1159               (success == GNUNET_OK) ? "success" : "FAILURE");
1160   if (NULL != mq->cont)
1161     mq->cont (mq->cont_cls, success);
1162   GNUNET_free (mq);
1163 }
1164
1165
1166 /**
1167  * Check the message list for the given neighbour and if we can
1168  * send a message, do so.  This function should only be called
1169  * if the connection is at least generally ready for transmission.
1170  * While we will only send one message at a time, no bandwidth
1171  * quota management is performed here.  If a message was given to
1172  * the plugin, the continuation will automatically re-schedule
1173  * the 'master' task once the next message might be transmitted.
1174  *
1175  * @param n target peer for which to transmit
1176  */
1177 static void
1178 try_transmission_to_peer (struct NeighbourMapEntry *n)
1179 {
1180   struct MessageQueue *mq;
1181   struct GNUNET_TIME_Relative timeout;
1182
1183   if (NULL == n->primary_address.address)
1184   {
1185     /* no address, why are we here? */
1186     GNUNET_break (0);
1187     return;
1188   }
1189   if ((0 == n->primary_address.address->address_length) && 
1190       (NULL == n->primary_address.session))
1191   {
1192     /* no address, why are we here? */
1193     GNUNET_break (0);
1194     return;
1195   }
1196   if (NULL != n->is_active)
1197   {
1198     /* transmission already pending */
1199     return;                     
1200   }
1201
1202   /* timeout messages from the queue that are past their due date */
1203   while (NULL != (mq = n->messages_head))
1204   {
1205     timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1206     if (timeout.rel_value > 0)
1207       break;
1208     GNUNET_STATISTICS_update (GST_stats,
1209                               gettext_noop
1210                               ("# messages timed out while in transport queue"),
1211                               1, GNUNET_NO);
1212     GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
1213     n->is_active = mq;
1214     transmit_send_continuation (mq, &n->id, GNUNET_SYSERR);     /* timeout */
1215   }
1216   if (NULL == mq)
1217     return;                     /* no more messages */
1218   GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
1219   n->is_active = mq;
1220   send_with_session (n,
1221                      mq->message_buf, mq->message_buf_size,
1222                      0 /* priority */, timeout,
1223                      &transmit_send_continuation, mq);
1224 }
1225
1226
1227 /**
1228  * Send keepalive message to the neighbour.  Must only be called
1229  * if we are on 'connected' state.  Will internally determine
1230  * if a keepalive is truly needed (so can always be called).
1231  *
1232  * @param n neighbour that went idle and needs a keepalive
1233  */
1234 static void
1235 send_keepalive (struct NeighbourMapEntry *n)
1236 {
1237   struct GNUNET_MessageHeader m;
1238
1239   GNUNET_assert (S_CONNECTED == n->state);
1240   if (GNUNET_TIME_absolute_get_remaining (n->keep_alive_time).rel_value > 0)
1241     return; /* no keepalive needed at this time */
1242   m.size = htons (sizeof (struct GNUNET_MessageHeader));
1243   m.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE);
1244   send_with_session (n,
1245                      (const void *) &m, sizeof (m),
1246                      UINT32_MAX /* priority */,
1247                      KEEPALIVE_FREQUENCY,
1248                      NULL, NULL);
1249   GNUNET_STATISTICS_update (GST_stats, gettext_noop ("# keepalives sent"), 1,
1250                             GNUNET_NO);
1251   n->expect_latency_response = GNUNET_YES;
1252   n->last_keep_alive_time = GNUNET_TIME_absolute_get ();
1253   n->keep_alive_time = GNUNET_TIME_relative_to_absolute (KEEPALIVE_FREQUENCY);
1254 }
1255
1256
1257 /**
1258  * Keep the connection to the given neighbour alive longer,
1259  * we received a KEEPALIVE (or equivalent); send a response.
1260  *
1261  * @param neighbour neighbour to keep alive (by sending keep alive response)
1262  */
1263 void
1264 GST_neighbours_keepalive (const struct GNUNET_PeerIdentity *neighbour)
1265 {
1266   struct NeighbourMapEntry *n;
1267   struct GNUNET_MessageHeader m;
1268
1269   if (NULL == (n = lookup_neighbour (neighbour)))
1270   {
1271     GNUNET_STATISTICS_update (GST_stats,
1272                               gettext_noop
1273                               ("# KEEPALIVE messages discarded (peer unknown)"),
1274                               1, GNUNET_NO);
1275     return;
1276   }
1277   if (NULL == n->primary_address.session)
1278   {
1279     GNUNET_STATISTICS_update (GST_stats,
1280                               gettext_noop
1281                               ("# KEEPALIVE messages discarded (no session)"),
1282                               1, GNUNET_NO);
1283     return;
1284   }
1285   /* send reply to allow neighbour to measure latency */
1286   m.size = htons (sizeof (struct GNUNET_MessageHeader));
1287   m.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE_RESPONSE);
1288   send_with_session(n,
1289                     (const void *) &m, sizeof (m),
1290                     UINT32_MAX /* priority */,
1291                     KEEPALIVE_FREQUENCY,
1292                     NULL, NULL);
1293 }
1294
1295
1296 /**
1297  * We received a KEEP_ALIVE_RESPONSE message and use this to calculate
1298  * latency to this peer.  Pass the updated information (existing ats
1299  * plus calculated latency) to ATS.
1300  *
1301  * @param neighbour neighbour to keep alive
1302  * @param ats performance data
1303  * @param ats_count number of entries in ats
1304  */
1305 void
1306 GST_neighbours_keepalive_response (const struct GNUNET_PeerIdentity *neighbour,
1307                                    const struct GNUNET_ATS_Information *ats,
1308                                    uint32_t ats_count)
1309 {
1310   struct NeighbourMapEntry *n;
1311   uint32_t latency;
1312   struct GNUNET_ATS_Information ats_new[ats_count + 1];
1313
1314   if (NULL == (n = lookup_neighbour (neighbour)))
1315   {
1316     GNUNET_STATISTICS_update (GST_stats,
1317                               gettext_noop
1318                               ("# KEEPALIVE_RESPONSE messages discarded (not connected)"),
1319                               1, GNUNET_NO);
1320     return;
1321   }
1322   if ( (S_CONNECTED != n->state) ||
1323        (GNUNET_YES != n->expect_latency_response) )
1324   {
1325     GNUNET_STATISTICS_update (GST_stats,
1326                               gettext_noop
1327                               ("# KEEPALIVE_RESPONSE messages discarded (not expected)"),
1328                               1, GNUNET_NO);
1329     return;
1330   }
1331   n->expect_latency_response = GNUNET_NO;
1332   n->latency = GNUNET_TIME_absolute_get_duration (n->last_keep_alive_time);
1333   n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1334   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1335               "Latency for peer `%s' is %llu ms\n",
1336               GNUNET_i2s (&n->id), n->latency.rel_value);
1337   memcpy (ats_new, ats, sizeof (struct GNUNET_ATS_Information) * ats_count);
1338   /* append latency */
1339   ats_new[ats_count].type = htonl (GNUNET_ATS_QUALITY_NET_DELAY);
1340   if (n->latency.rel_value > UINT32_MAX)
1341     latency = UINT32_MAX;
1342   else
1343     latency = n->latency.rel_value;
1344   ats_new[ats_count].value = htonl (latency);
1345   GNUNET_ATS_address_update (GST_ats, 
1346                              n->primary_address.address, 
1347                              n->primary_address.session, ats_new,
1348                              ats_count + 1);
1349 }
1350
1351
1352 /**
1353  * We have received a message from the given sender.  How long should
1354  * we delay before receiving more?  (Also used to keep the peer marked
1355  * as live).
1356  *
1357  * @param sender sender of the message
1358  * @param size size of the message
1359  * @param do_forward set to GNUNET_YES if the message should be forwarded to clients
1360  *                   GNUNET_NO if the neighbour is not connected or violates the quota,
1361  *                   GNUNET_SYSERR if the connection is not fully up yet
1362  * @return how long to wait before reading more from this sender
1363  */
1364 struct GNUNET_TIME_Relative
1365 GST_neighbours_calculate_receive_delay (const struct GNUNET_PeerIdentity
1366                                         *sender, ssize_t size, int *do_forward)
1367 {
1368   struct NeighbourMapEntry *n;
1369   struct GNUNET_TIME_Relative ret;
1370   
1371   if (NULL == neighbours)
1372   {
1373     *do_forward = GNUNET_NO;
1374     return GNUNET_TIME_UNIT_FOREVER_REL; /* This can happen during shutdown */
1375   }
1376   if (NULL == (n = lookup_neighbour (sender)))
1377   {
1378     GST_neighbours_try_connect (sender);
1379     if (NULL == (n = lookup_neighbour (sender)))
1380     {
1381       GNUNET_STATISTICS_update (GST_stats,
1382                                 gettext_noop
1383                                 ("# messages discarded due to lack of neighbour record"),
1384                                 1, GNUNET_NO);
1385       *do_forward = GNUNET_NO;
1386       return GNUNET_TIME_UNIT_ZERO;
1387     }
1388   }
1389   if (! test_connected (n))
1390   {
1391     *do_forward = GNUNET_SYSERR;
1392     return GNUNET_TIME_UNIT_ZERO;
1393   }
1394   if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, size))
1395   {
1396     n->quota_violation_count++;
1397     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1398                 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
1399                 n->in_tracker.available_bytes_per_s__,
1400                 n->quota_violation_count);
1401     /* Discount 32k per violation */
1402     GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, -32 * 1024);
1403   }
1404   else
1405   {
1406     if (n->quota_violation_count > 0)
1407     {
1408       /* try to add 32k back */
1409       GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, 32 * 1024);
1410       n->quota_violation_count--;
1411     }
1412   }
1413   if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
1414   {
1415     GNUNET_STATISTICS_update (GST_stats,
1416                               gettext_noop
1417                               ("# bandwidth quota violations by other peers"),
1418                               1, GNUNET_NO);
1419     *do_forward = GNUNET_NO;
1420     return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
1421   }
1422   *do_forward = GNUNET_YES;
1423   ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 32 * 1024);
1424   if (ret.rel_value > 0)
1425   {
1426     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1427                 "Throttling read (%llu bytes excess at %u b/s), waiting %llu ms before reading more.\n",
1428                 (unsigned long long) n->in_tracker.
1429                 consumption_since_last_update__,
1430                 (unsigned int) n->in_tracker.available_bytes_per_s__,
1431                 (unsigned long long) ret.rel_value);
1432     GNUNET_STATISTICS_update (GST_stats,
1433                               gettext_noop ("# ms throttling suggested"),
1434                               (int64_t) ret.rel_value, GNUNET_NO);
1435   }
1436   return ret;
1437 }
1438
1439
1440 /**
1441  * Transmit a message to the given target using the active connection.
1442  *
1443  * @param target destination
1444  * @param msg message to send
1445  * @param msg_size number of bytes in msg
1446  * @param timeout when to fail with timeout
1447  * @param cont function to call when done
1448  * @param cont_cls closure for 'cont'
1449  */
1450 void
1451 GST_neighbours_send (const struct GNUNET_PeerIdentity *target, const void *msg,
1452                      size_t msg_size, struct GNUNET_TIME_Relative timeout,
1453                      GST_NeighbourSendContinuation cont, void *cont_cls)
1454 {
1455   struct NeighbourMapEntry *n;
1456   struct MessageQueue *mq;
1457
1458   /* All ove these cases should never happen; they are all API violations.
1459      But we check anyway, just to be sure. */
1460   if (NULL == (n = lookup_neighbour (target)))
1461   {
1462     GNUNET_break (0);
1463     if (NULL != cont)
1464       cont (cont_cls, GNUNET_SYSERR);
1465     return;
1466   }
1467   if (GNUNET_YES != test_connected (n))
1468   {
1469     GNUNET_break (0);
1470     if (NULL != cont)
1471       cont (cont_cls, GNUNET_SYSERR);
1472     return;
1473   }
1474   bytes_in_send_queue += msg_size;
1475   GNUNET_STATISTICS_set (GST_stats,
1476                          gettext_noop
1477                          ("# bytes in message queue for other peers"),
1478                          bytes_in_send_queue, GNUNET_NO);
1479   mq = GNUNET_malloc (sizeof (struct MessageQueue) + msg_size);
1480   mq->cont = cont;
1481   mq->cont_cls = cont_cls;
1482   memcpy (&mq[1], msg, msg_size);
1483   mq->message_buf = (const char *) &mq[1];
1484   mq->message_buf_size = msg_size;
1485   mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1486   GNUNET_CONTAINER_DLL_insert_tail (n->messages_head, n->messages_tail, mq);
1487   if ( (NULL != n->is_active) ||
1488        ( (NULL == n->primary_address.session) && (NULL == n->primary_address.address)) )
1489     return;
1490   GNUNET_SCHEDULER_cancel (n->task);
1491   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
1492 }
1493
1494
1495 /**
1496  * Send a SESSION_CONNECT message via the given address.
1497  *
1498  * @param na address to use
1499  */
1500 static void
1501 send_session_connect (struct NeighbourAddress *na)
1502 {
1503   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1504   struct SessionConnectMessage connect_msg;
1505   
1506   if (NULL == (papi = GST_plugins_find (na->address->transport_name)))  
1507   {
1508     GNUNET_break (0);
1509     return;
1510   }
1511   if (NULL == na->session)
1512     na->session = papi->get_session (papi->cls, na->address);    
1513   if (NULL == na->session)
1514   {
1515     GNUNET_break (0);
1516     return;
1517   }
1518   na->connect_timestamp = GNUNET_TIME_absolute_get ();
1519   connect_msg.header.size = htons (sizeof (struct SessionConnectMessage));
1520   connect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT);
1521   connect_msg.reserved = htonl (0);
1522   connect_msg.timestamp = GNUNET_TIME_absolute_hton (na->connect_timestamp);
1523   (void) papi->send (papi->cls,
1524                      na->session,
1525                      (const char *) &connect_msg, sizeof (struct SessionConnectMessage),
1526                      UINT_MAX,
1527                      GNUNET_TIME_UNIT_FOREVER_REL,
1528                      NULL, NULL);
1529 }
1530
1531
1532 /**
1533  * Send a SESSION_CONNECT_ACK message via the given address.
1534  *
1535  * @param address address to use
1536  * @param session session to use
1537  * @param timestamp timestamp to use for the ACK message
1538  */
1539 static void
1540 send_session_connect_ack_message (const struct GNUNET_HELLO_Address *address,
1541                                   struct Session *session,
1542                                   struct GNUNET_TIME_Absolute timestamp)
1543 {
1544   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1545   struct SessionConnectMessage connect_msg;
1546   
1547   if (NULL == (papi = GST_plugins_find (address->transport_name)))  
1548   {
1549     GNUNET_break (0);
1550     return;
1551   }
1552   if (NULL == session)
1553     session = papi->get_session (papi->cls, address);    
1554   if (NULL == session)
1555   {
1556     GNUNET_break (0);
1557     return;
1558   }
1559   connect_msg.header.size = htons (sizeof (struct SessionConnectMessage));
1560   connect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT_ACK);
1561   connect_msg.reserved = htonl (0);
1562   connect_msg.timestamp = GNUNET_TIME_absolute_hton (timestamp);
1563   (void) papi->send (papi->cls,
1564                      session,
1565                      (const char *) &connect_msg, sizeof (struct SessionConnectMessage),
1566                      UINT_MAX,
1567                      GNUNET_TIME_UNIT_FOREVER_REL,
1568                      NULL, NULL);
1569 }
1570
1571
1572 /**
1573  * Create a fresh entry in the neighbour map for the given peer
1574  *
1575  * @param peer peer to create an entry for
1576  * @return new neighbour map entry
1577  */
1578 static struct NeighbourMapEntry *
1579 setup_neighbour (const struct GNUNET_PeerIdentity *peer)
1580 {
1581   struct NeighbourMapEntry *n;
1582
1583   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1584               "Creating new neighbour entry for `%s'\n", 
1585               GNUNET_i2s (peer));
1586   n = GNUNET_malloc (sizeof (struct NeighbourMapEntry));
1587   n->id = *peer;
1588   n->state = S_NOT_CONNECTED;
1589   n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
1590   GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
1591                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
1592                                  MAX_BANDWIDTH_CARRY_S);
1593   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
1594   GNUNET_assert (GNUNET_OK ==
1595                  GNUNET_CONTAINER_multihashmap_put (neighbours,
1596                                                     &n->id.hashPubKey, n,
1597                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1598   return n;
1599 }
1600
1601
1602 /**
1603  * Check if the two given addresses are the same.
1604  * Actually only checks if the sessions are non-NULL
1605  * (which they should be) and then if they are identical;
1606  * the actual addresses don't matter if the session
1607  * pointers match anyway, and we must have session pointers
1608  * at this time.
1609  *
1610  * @param a1 first address to compare
1611  * @param a2 other address to compare
1612  * @return GNUNET_NO if the addresses do not match, GNUNET_YES if they do match
1613  */
1614 static int
1615 address_matches (const struct NeighbourAddress *a1,
1616                  const struct NeighbourAddress *a2)
1617 {
1618   if ( (NULL == a1->session) ||
1619        (NULL == a2->session) )
1620   {
1621     GNUNET_break (0);
1622     return 0;
1623   }
1624   return (a1->session == a2->session) ? GNUNET_YES : GNUNET_NO;
1625 }
1626
1627
1628 /**
1629  * Try to create a connection to the given target (eventually).
1630  *
1631  * @param target peer to try to connect to
1632  */
1633 void
1634 GST_neighbours_try_connect (const struct GNUNET_PeerIdentity *target)
1635 {
1636   struct NeighbourMapEntry *n;
1637
1638   if (NULL == neighbours)  
1639     return; /* during shutdown, do nothing */
1640   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1641               "Asked to connect to peer `%s'\n",
1642               GNUNET_i2s (target));
1643   if (0 ==
1644       memcmp (target, &GST_my_identity, sizeof (struct GNUNET_PeerIdentity)))
1645   {
1646     /* refuse to connect to myself */
1647     /* FIXME: can this happen? Is this not an API violation? */
1648     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1649                 "Refusing to try to connect to myself.\n");
1650     return;
1651   }
1652   n = lookup_neighbour (target);
1653   if (NULL != n)
1654   {
1655     switch (n->state)
1656     {
1657     case S_NOT_CONNECTED:
1658       /* this should not be possible */
1659       GNUNET_break (0);
1660       free_neighbour (n, GNUNET_NO);
1661       break;
1662     case S_INIT_ATS:
1663     case S_INIT_BLACKLIST:
1664     case S_CONNECT_SENT:
1665     case S_CONNECT_RECV_ATS:
1666     case S_CONNECT_RECV_BLACKLIST:
1667     case S_CONNECT_RECV_ACK:
1668       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1669                   "Ignoring request to try to connect to `%s', already trying!\n",
1670                   GNUNET_i2s (target));
1671       return; /* already trying */
1672     case S_CONNECTED:      
1673     case S_RECONNECT_ATS:
1674     case S_RECONNECT_BLACKLIST:
1675     case S_RECONNECT_SENT:
1676     case S_CONNECTED_SWITCHING_BLACKLIST:
1677     case S_CONNECTED_SWITCHING_CONNECT_SENT:
1678       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1679                   "Ignoring request to try to connect, already connected to `%s'!\n",
1680                   GNUNET_i2s (target));
1681       return; /* already connected */
1682     case S_DISCONNECT:
1683       /* get rid of remains, ready to re-try immediately */
1684       free_neighbour (n, GNUNET_NO);
1685       break;
1686     case S_DISCONNECT_FINISHED:
1687       /* should not be possible */      
1688       GNUNET_assert (0); 
1689     default:
1690       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
1691       GNUNET_break (0);
1692       free_neighbour (n, GNUNET_NO);
1693       break;
1694     }
1695   }
1696   n = setup_neighbour (target);  
1697   n->state = S_INIT_ATS; 
1698   n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1699
1700   GNUNET_ATS_reset_backoff (GST_ats, target);
1701   GNUNET_ATS_suggest_address (GST_ats, target);
1702 }
1703
1704
1705 /**
1706  * Function called with the result of a blacklist check.
1707  *
1708  * @param cls closure with the 'struct BlackListCheckContext'
1709  * @param peer peer this check affects
1710  * @param result GNUNET_OK if the address is allowed
1711  */
1712 static void
1713 handle_test_blacklist_cont (void *cls,
1714                             const struct GNUNET_PeerIdentity *peer,
1715                             int result)
1716 {
1717   struct BlackListCheckContext *bcc = cls;
1718   struct NeighbourMapEntry *n;
1719
1720   bcc->bc = NULL;
1721   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1722               "Connection to new address of peer `%s' based on blacklist is `%s'\n",
1723               GNUNET_i2s (peer),
1724               (GNUNET_OK == result) ? "allowed" : "FORBIDDEN");
1725   if (GNUNET_OK == result)
1726   {
1727     /* valid new address, let ATS know! */
1728     GNUNET_ATS_address_update (GST_ats, 
1729                                bcc->na.address, 
1730                                bcc->na.session, 
1731                                bcc->ats, bcc->ats_count);
1732   }
1733   if (NULL == (n = lookup_neighbour (peer)))
1734     goto cleanup; /* nobody left to care about new address */
1735   switch (n->state)
1736   {
1737   case S_NOT_CONNECTED:
1738     /* this should not be possible */
1739     GNUNET_break (0);
1740     free_neighbour (n, GNUNET_NO);
1741     break;
1742   case S_INIT_ATS:
1743     /* still waiting on ATS suggestion */
1744     break;
1745   case S_INIT_BLACKLIST:
1746     /* check if the address the blacklist was fine with matches
1747        ATS suggestion, if so, we can move on! */
1748     if ( (GNUNET_OK == result) &&
1749          (1 == n->send_connect_ack) )
1750     {
1751       n->send_connect_ack = 2;
1752       send_session_connect_ack_message (bcc->na.address,
1753                                         bcc->na.session,
1754                                         n->connect_ack_timestamp);
1755     }
1756     if (GNUNET_YES != address_matches (&bcc->na, &n->primary_address))
1757       break; /* result for an address we currently don't care about */
1758     if (GNUNET_OK == result)
1759     {
1760       n->timeout = GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT);
1761       n->state = S_CONNECT_SENT;
1762       send_session_connect (&n->primary_address);
1763     }
1764     else
1765     {
1766       GNUNET_ATS_address_destroyed (GST_ats,
1767                                     bcc->na.address,
1768                                     NULL);
1769       n->state = S_INIT_ATS;
1770       n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1771       // FIXME: do we need to ask ATS again for suggestions?
1772       GNUNET_ATS_suggest_address (GST_ats, &n->id);
1773     }
1774     break;
1775   case S_CONNECT_SENT:
1776     /* waiting on CONNECT_ACK, send ACK if one is pending */
1777     if ( (GNUNET_OK == result) &&
1778          (1 == n->send_connect_ack) )
1779     {
1780       n->send_connect_ack = 2;
1781       send_session_connect_ack_message (n->primary_address.address,
1782                                         n->primary_address.session,
1783                                         n->connect_ack_timestamp);
1784     }
1785     break; 
1786   case S_CONNECT_RECV_ATS:
1787     /* still waiting on ATS suggestion, don't care about blacklist */
1788     break; 
1789   case S_CONNECT_RECV_BLACKLIST:
1790     if (GNUNET_YES != address_matches (&bcc->na, &n->primary_address))
1791       break; /* result for an address we currently don't care about */
1792     if (GNUNET_OK == result)
1793     {
1794       n->timeout = GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT);
1795       n->state = S_CONNECT_RECV_ACK;
1796       send_session_connect_ack_message (bcc->na.address,
1797                                         bcc->na.session,
1798                                         n->connect_ack_timestamp);
1799       if (1 == n->send_connect_ack) 
1800         n->send_connect_ack = 2;
1801     }
1802     else
1803     {
1804       GNUNET_ATS_address_destroyed (GST_ats,
1805                                     bcc->na.address,
1806                                     NULL);
1807       n->state = S_INIT_ATS;
1808       n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1809       // FIXME: do we need to ask ATS again for suggestions?
1810       GNUNET_ATS_reset_backoff (GST_ats, peer);
1811       GNUNET_ATS_suggest_address (GST_ats, &n->id);
1812     }
1813     break;
1814   case S_CONNECT_RECV_ACK:
1815     /* waiting on SESSION_ACK, send ACK if one is pending */
1816     if ( (GNUNET_OK == result) &&
1817          (1 == n->send_connect_ack) )
1818     {
1819       n->send_connect_ack = 2;
1820       send_session_connect_ack_message (n->primary_address.address,
1821                                         n->primary_address.session,
1822                                         n->connect_ack_timestamp);
1823     }
1824     break; 
1825   case S_CONNECTED:
1826     /* already connected, don't care about blacklist */
1827     break;
1828   case S_RECONNECT_ATS:
1829     /* still waiting on ATS suggestion, don't care about blacklist */
1830     break;     
1831   case S_RECONNECT_BLACKLIST:
1832     if ( (GNUNET_OK == result) &&
1833          (1 == n->send_connect_ack) )
1834     {
1835       n->send_connect_ack = 2;
1836       send_session_connect_ack_message (bcc->na.address,
1837                                         bcc->na.session,
1838                                         n->connect_ack_timestamp);
1839     }
1840     if (GNUNET_YES != address_matches (&bcc->na, &n->primary_address))
1841       break; /* result for an address we currently don't care about */
1842     if (GNUNET_OK == result)
1843     {
1844       send_session_connect (&n->primary_address);
1845       n->timeout = GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT);
1846       n->state = S_RECONNECT_SENT;
1847     }
1848     else
1849     {
1850       GNUNET_ATS_address_destroyed (GST_ats,
1851                                     bcc->na.address,
1852                                     NULL);
1853       n->state = S_RECONNECT_ATS;
1854       n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1855       // FIXME: do we need to ask ATS again for suggestions?
1856       GNUNET_ATS_suggest_address (GST_ats, &n->id);
1857     }
1858     break;
1859   case S_RECONNECT_SENT:
1860     /* waiting on CONNECT_ACK, don't care about blacklist */
1861     if ( (GNUNET_OK == result) &&
1862          (1 == n->send_connect_ack) )
1863     {
1864       n->send_connect_ack = 2;
1865       send_session_connect_ack_message (n->primary_address.address,
1866                                         n->primary_address.session,
1867                                         n->connect_ack_timestamp);
1868     }
1869     break;     
1870   case S_CONNECTED_SWITCHING_BLACKLIST:
1871     if (GNUNET_YES != address_matches (&bcc->na, &n->alternative_address))
1872       break; /* result for an address we currently don't care about */
1873     if (GNUNET_OK == result)
1874     {
1875       send_session_connect (&n->alternative_address);
1876       n->state = S_CONNECTED_SWITCHING_CONNECT_SENT;
1877     }
1878     else
1879     {
1880       GNUNET_ATS_address_destroyed (GST_ats,
1881                                     bcc->na.address,
1882                                     NULL);
1883       free_address (&n->alternative_address);
1884       n->state = S_CONNECTED;
1885     }
1886     break;
1887   case S_CONNECTED_SWITCHING_CONNECT_SENT:
1888     /* waiting on CONNECT_ACK, don't care about blacklist */
1889     if ( (GNUNET_OK == result) &&
1890          (1 == n->send_connect_ack) )
1891     {
1892       n->send_connect_ack = 2;
1893       send_session_connect_ack_message (n->primary_address.address,
1894                                         n->primary_address.session,
1895                                         n->connect_ack_timestamp);
1896     }
1897     break;     
1898   case S_DISCONNECT:
1899     /* Nothing to do here, ATS will already do what can be done */
1900     break;
1901   case S_DISCONNECT_FINISHED:
1902     /* should not be possible */
1903     GNUNET_assert (0);
1904     break;
1905   default:
1906     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
1907     GNUNET_break (0);
1908     free_neighbour (n, GNUNET_NO);
1909     break;
1910   }
1911  cleanup:
1912   GNUNET_HELLO_address_free (bcc->na.address);
1913   GNUNET_CONTAINER_DLL_remove (bc_head,
1914                                bc_tail,
1915                                bcc);
1916   GNUNET_free (bcc);
1917 }
1918
1919
1920 /**
1921  * We want to know if connecting to a particular peer via
1922  * a particular address is allowed.  Check it!
1923  *
1924  * @param peer identity of the peer to switch the address for
1925  * @param ts time at which the check was initiated
1926  * @param address address of the other peer, NULL if other peer
1927  *                       connected to us
1928  * @param session session to use (or NULL)
1929  * @param ats performance data
1930  * @param ats_count number of entries in ats (excluding 0-termination)
1931  */
1932 static void
1933 check_blacklist (const struct GNUNET_PeerIdentity *peer,
1934                  struct GNUNET_TIME_Absolute ts,
1935                  const struct GNUNET_HELLO_Address *address,
1936                  struct Session *session,
1937                  const struct GNUNET_ATS_Information *ats,
1938                  uint32_t ats_count)
1939 {
1940   struct BlackListCheckContext *bcc;
1941   struct GST_BlacklistCheck *bc;
1942
1943   bcc =
1944       GNUNET_malloc (sizeof (struct BlackListCheckContext) +
1945                      sizeof (struct GNUNET_ATS_Information) * ats_count);
1946   bcc->ats_count = ats_count;
1947   bcc->na.address = GNUNET_HELLO_address_copy (address);
1948   bcc->na.session = session;
1949   bcc->na.connect_timestamp = ts;
1950   bcc->ats = (struct GNUNET_ATS_Information *) &bcc[1];
1951   memcpy (bcc->ats, ats, sizeof (struct GNUNET_ATS_Information) * ats_count);
1952   GNUNET_CONTAINER_DLL_insert (bc_head,
1953                                bc_tail,
1954                                bcc);
1955   if (NULL != (bc = GST_blacklist_test_allowed (peer, 
1956                                                 address->transport_name,
1957                                                 &handle_test_blacklist_cont, bcc)))
1958     bcc->bc = bc; 
1959   /* if NULL == bc, 'cont' was already called and 'bcc' already free'd, so
1960      we must only store 'bc' if 'bc' is non-NULL... */
1961 }
1962
1963
1964 /**
1965  * We received a 'SESSION_CONNECT' message from the other peer.
1966  * Consider switching to it.
1967  *
1968  * @param message possibly a 'struct SessionConnectMessage' (check format)
1969  * @param peer identity of the peer to switch the address for
1970  * @param address address of the other peer, NULL if other peer
1971  *                       connected to us
1972  * @param session session to use (or NULL)
1973  * @param ats performance data
1974  * @param ats_count number of entries in ats (excluding 0-termination)
1975  */
1976 void
1977 GST_neighbours_handle_connect (const struct GNUNET_MessageHeader *message,
1978                                const struct GNUNET_PeerIdentity *peer,
1979                                const struct GNUNET_HELLO_Address *address,
1980                                struct Session *session,
1981                                const struct GNUNET_ATS_Information *ats,
1982                                uint32_t ats_count)
1983 {
1984   const struct SessionConnectMessage *scm;
1985   struct NeighbourMapEntry *n;
1986   struct GNUNET_TIME_Absolute ts;
1987
1988   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1989               "Received CONNECT message from peer `%s'\n", 
1990               GNUNET_i2s (peer));
1991   if (ntohs (message->size) != sizeof (struct SessionConnectMessage))
1992   {
1993     GNUNET_break_op (0);
1994     return;
1995   }
1996   if (NULL == neighbours)
1997     return; /* we're shutting down */
1998   scm = (const struct SessionConnectMessage *) message;
1999   GNUNET_break_op (0 == ntohl (scm->reserved));
2000   ts = GNUNET_TIME_absolute_ntoh (scm->timestamp);
2001   n = lookup_neighbour (peer);
2002   if (NULL == n)
2003     n = setup_neighbour (peer);
2004   n->send_connect_ack = 1;
2005   n->connect_ack_timestamp = ts;
2006   switch (n->state)
2007   {  
2008   case S_NOT_CONNECTED:
2009     n->state = S_CONNECT_RECV_ATS;
2010     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
2011     GNUNET_ATS_reset_backoff (GST_ats, peer);
2012     GNUNET_ATS_suggest_address (GST_ats, peer);
2013     check_blacklist (peer, ts, address, session, ats, ats_count);
2014     break;
2015   case S_INIT_ATS:
2016   case S_INIT_BLACKLIST:
2017   case S_CONNECT_SENT:
2018   case S_CONNECT_RECV_ATS:
2019   case S_CONNECT_RECV_BLACKLIST:
2020   case S_CONNECT_RECV_ACK:
2021     /* It can never hurt to have an alternative address in the above cases, 
2022        see if it is allowed */
2023     check_blacklist (peer, ts, address, session, ats, ats_count);
2024     break;
2025   case S_CONNECTED:
2026     /* we are already connected and can thus send the ACK immediately;
2027        still, it can never hurt to have an alternative address, so also
2028        tell ATS  about it */
2029     GNUNET_assert (NULL != n->primary_address.address);
2030     GNUNET_assert (NULL != n->primary_address.session);
2031     n->send_connect_ack = 0;
2032     send_session_connect_ack_message (n->primary_address.address,
2033                                       n->primary_address.session, ts);
2034     check_blacklist (peer, ts, address, session, ats, ats_count);
2035     break;
2036   case S_RECONNECT_ATS:
2037   case S_RECONNECT_BLACKLIST:
2038   case S_RECONNECT_SENT:
2039     /* It can never hurt to have an alternative address in the above cases, 
2040        see if it is allowed */
2041     check_blacklist (peer, ts, address, session, ats, ats_count);
2042     break;
2043   case S_CONNECTED_SWITCHING_BLACKLIST:
2044   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2045     /* we are already connected and can thus send the ACK immediately;
2046        still, it can never hurt to have an alternative address, so also
2047        tell ATS  about it */
2048     GNUNET_assert (NULL != n->primary_address.address);
2049     GNUNET_assert (NULL != n->primary_address.session);
2050     n->send_connect_ack = 0;
2051     send_session_connect_ack_message (n->primary_address.address,
2052                                       n->primary_address.session, ts);
2053     check_blacklist (peer, ts, address, session, ats, ats_count);
2054     break;
2055   case S_DISCONNECT:
2056     /* get rid of remains without terminating sessions, ready to re-try */
2057     free_neighbour (n, GNUNET_YES);
2058     n = setup_neighbour (peer);
2059     n->state = S_CONNECT_RECV_ATS;
2060     GNUNET_ATS_reset_backoff (GST_ats, peer);
2061     GNUNET_ATS_suggest_address (GST_ats, peer);
2062     break;
2063   case S_DISCONNECT_FINISHED:
2064     /* should not be possible */
2065     GNUNET_assert (0);
2066     break;
2067   default:
2068     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2069     GNUNET_break (0);
2070     free_neighbour (n, GNUNET_NO);
2071     break;
2072   }
2073 }
2074
2075
2076 /**
2077  * For an existing neighbour record, set the active connection to
2078  * use the given address.  
2079  *
2080  * @param peer identity of the peer to switch the address for
2081  * @param address address of the other peer, NULL if other peer
2082  *                       connected to us
2083  * @param session session to use (or NULL)
2084  * @param ats performance data
2085  * @param ats_count number of entries in ats
2086  * @param bandwidth_in inbound quota to be used when connection is up
2087  * @param bandwidth_out outbound quota to be used when connection is up
2088  */
2089 void
2090 GST_neighbours_switch_to_address (const struct GNUNET_PeerIdentity *peer,
2091                                   const struct GNUNET_HELLO_Address *address,
2092                                   struct Session *session,
2093                                   const struct GNUNET_ATS_Information *ats,
2094                                   uint32_t ats_count,
2095                                   struct GNUNET_BANDWIDTH_Value32NBO
2096                                   bandwidth_in,
2097                                   struct GNUNET_BANDWIDTH_Value32NBO
2098                                   bandwidth_out)
2099 {
2100   struct NeighbourMapEntry *n;
2101   struct GNUNET_TRANSPORT_PluginFunctions *papi;
2102
2103   GNUNET_assert (address->transport_name != NULL);
2104   if (NULL == (n = lookup_neighbour (peer)))
2105     return;
2106
2107   /* Obtain an session for this address from plugin */
2108   if (NULL == (papi = GST_plugins_find (address->transport_name)))
2109   {
2110     /* we don't have the plugin for this address */
2111     GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
2112     return;
2113   }
2114   if ((NULL == session) && (0 == address->address_length))
2115   {
2116     GNUNET_break (0);
2117     if (strlen (address->transport_name) > 0)
2118       GNUNET_ATS_address_destroyed (GST_ats, address, session);
2119     return;
2120   }
2121   if (NULL == session)
2122     session = papi->get_session (papi->cls, address);
2123   if (NULL == session)
2124   {
2125     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2126                 "Failed to obtain new session for peer `%s' and  address '%s'\n",
2127                 GNUNET_i2s (&address->peer), GST_plugins_a2s (address));    
2128     GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
2129     return;
2130   }
2131   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2132               "ATS tells us to switch to address '%s' for peer `%s'\n",
2133               (address->address_length != 0) ? GST_plugins_a2s (address): "<inbound>",
2134               GNUNET_i2s (peer));
2135   switch (n->state)
2136   {
2137   case S_NOT_CONNECTED:
2138     GNUNET_break (0);
2139     free_neighbour (n, GNUNET_NO);
2140     return;
2141   case S_INIT_ATS:
2142     set_address (&n->primary_address,
2143                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2144     n->state = S_INIT_BLACKLIST;
2145     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2146     check_blacklist (&n->id,
2147                      n->connect_ack_timestamp,
2148                      address, session, ats, ats_count);    
2149     break;
2150   case S_INIT_BLACKLIST:
2151     /* ATS suggests a different address, switch again */
2152     set_address (&n->primary_address,
2153                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2154     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2155     check_blacklist (&n->id,
2156                      n->connect_ack_timestamp,
2157                      address, session, ats, ats_count);    
2158     break;
2159   case S_CONNECT_SENT:
2160     /* ATS suggests a different address, switch again */
2161     set_address (&n->primary_address,
2162                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2163     n->state = S_INIT_BLACKLIST;
2164     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2165     check_blacklist (&n->id,
2166                      n->connect_ack_timestamp,
2167                      address, session, ats, ats_count);    
2168     break;
2169   case S_CONNECT_RECV_ATS:
2170     set_address (&n->primary_address,
2171                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2172     n->state = S_CONNECT_RECV_BLACKLIST;
2173     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2174     check_blacklist (&n->id,
2175                      n->connect_ack_timestamp,
2176                      address, session, ats, ats_count);    
2177     break;
2178   case S_CONNECT_RECV_BLACKLIST:
2179   case S_CONNECT_RECV_ACK:
2180     /* ATS asks us to switch while we were trying to connect; switch to new
2181        address and check blacklist again */
2182     set_address (&n->primary_address,
2183                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2184     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2185     check_blacklist (&n->id,
2186                      n->connect_ack_timestamp,
2187                      address, session, ats, ats_count);    
2188     break;
2189   case S_CONNECTED:
2190     GNUNET_assert (NULL != n->primary_address.address);
2191     GNUNET_assert (NULL != n->primary_address.session);
2192     if (n->primary_address.session == session)
2193     {
2194       /* not an address change, just a quota change */
2195       set_address (&n->primary_address,
2196                    address, session, bandwidth_in, bandwidth_out, GNUNET_YES);
2197       break;
2198     }
2199     /* ATS asks us to switch a life connection; see if we can get
2200        a CONNECT_ACK on it before we actually do this! */
2201     set_address (&n->alternative_address,
2202                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2203     n->state = S_CONNECTED_SWITCHING_BLACKLIST;
2204     check_blacklist (&n->id,
2205                      GNUNET_TIME_absolute_get (),
2206                      address, session, ats, ats_count);
2207     break;
2208   case S_RECONNECT_ATS:
2209     set_address (&n->primary_address,
2210                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2211     n->state = S_RECONNECT_BLACKLIST;
2212     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2213     check_blacklist (&n->id,
2214                      n->connect_ack_timestamp,
2215                      address, session, ats, ats_count);    
2216     break;
2217   case S_RECONNECT_BLACKLIST:
2218     /* ATS asks us to switch while we were trying to reconnect; switch to new
2219        address and check blacklist again */
2220     set_address (&n->primary_address,
2221                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2222     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2223     check_blacklist (&n->id,
2224                      n->connect_ack_timestamp,
2225                      address, session, ats, ats_count);    
2226     break;
2227   case S_RECONNECT_SENT:
2228     /* ATS asks us to switch while we were trying to reconnect; switch to new
2229        address and check blacklist again */
2230     set_address (&n->primary_address,
2231                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2232     n->state = S_RECONNECT_BLACKLIST;
2233     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2234     check_blacklist (&n->id,
2235                      n->connect_ack_timestamp,
2236                      address, session, ats, ats_count); 
2237     break;
2238   case S_CONNECTED_SWITCHING_BLACKLIST:
2239     if (n->primary_address.session == session)
2240     {
2241       /* ATS switches back to still-active session */
2242       free_address (&n->alternative_address);
2243       n->state = S_CONNECTED;
2244       break;
2245     }
2246     /* ATS asks us to switch a life connection, update blacklist check */
2247     set_address (&n->alternative_address,
2248                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2249     check_blacklist (&n->id,
2250                      GNUNET_TIME_absolute_get (),
2251                      address, session, ats, ats_count);
2252     break;
2253   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2254     if (n->primary_address.session == session)
2255     {
2256       /* ATS switches back to still-active session */
2257       free_address (&n->alternative_address);
2258       n->state = S_CONNECTED;
2259       break;
2260     }
2261     /* ATS asks us to switch a life connection, update blacklist check */
2262     set_address (&n->alternative_address,
2263                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2264     n->state = S_CONNECTED_SWITCHING_BLACKLIST;
2265     check_blacklist (&n->id,
2266                      GNUNET_TIME_absolute_get (),
2267                      address, session, ats, ats_count);
2268     break;
2269   case S_DISCONNECT:
2270     /* not going to switch addresses while disconnecting */
2271     return;
2272   case S_DISCONNECT_FINISHED:
2273     GNUNET_assert (0);
2274     break;
2275   default:
2276     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2277     GNUNET_break (0);
2278     break;
2279   }
2280 }
2281
2282
2283 /**
2284  * Master task run for every neighbour.  Performs all of the time-related
2285  * activities (keep alive, send next message, disconnect if idle, finish
2286  * clean up after disconnect).
2287  *
2288  * @param cls the 'struct NeighbourMapEntry' for which we are running
2289  * @param tc scheduler context (unused)
2290  */
2291 static void
2292 master_task (void *cls,
2293              const struct GNUNET_SCHEDULER_TaskContext *tc)
2294 {
2295   struct NeighbourMapEntry *n = cls;
2296   struct GNUNET_TIME_Relative delay;
2297
2298   n->task = GNUNET_SCHEDULER_NO_TASK;
2299   delay = GNUNET_TIME_absolute_get_remaining (n->timeout);  
2300   switch (n->state)
2301   {
2302   case S_NOT_CONNECTED:
2303     /* invalid state for master task, clean up */
2304     GNUNET_break (0);
2305     n->state = S_DISCONNECT_FINISHED;
2306     free_neighbour (n, GNUNET_NO);
2307     return;
2308   case S_INIT_ATS:
2309     if (0 == delay.rel_value)
2310     {
2311       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2312                   "Connection to `%s' timed out waiting for ATS to provide address\n",
2313                   GNUNET_i2s (&n->id));
2314       n->state = S_DISCONNECT_FINISHED;
2315       free_neighbour (n, GNUNET_NO);
2316       return;
2317     }
2318     break;
2319   case S_INIT_BLACKLIST:
2320     if (0 == delay.rel_value)
2321     {
2322       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2323                   "Connection to `%s' timed out waiting for BLACKLIST to approve address\n",
2324                   GNUNET_i2s (&n->id));
2325       n->state = S_DISCONNECT_FINISHED;
2326       free_neighbour (n, GNUNET_NO);
2327       return;
2328     }
2329     break;
2330   case S_CONNECT_SENT:
2331     if (0 == delay.rel_value)
2332     {
2333       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2334                   "Connection to `%s' timed out waiting for other peer to send CONNECT_ACK\n",
2335                   GNUNET_i2s (&n->id));
2336       disconnect_neighbour (n);
2337       return;
2338     }
2339     break;
2340   case S_CONNECT_RECV_ATS:
2341     if (0 == delay.rel_value)
2342     {
2343       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2344                   "Connection to `%s' timed out waiting ATS to provide address to use for CONNECT_ACK\n",
2345                   GNUNET_i2s (&n->id));
2346       n->state = S_DISCONNECT_FINISHED;
2347       free_neighbour (n, GNUNET_NO);
2348       return;
2349     }
2350     break;
2351   case S_CONNECT_RECV_BLACKLIST:
2352     if (0 == delay.rel_value)
2353     {
2354       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2355                   "Connection to `%s' timed out waiting BLACKLIST to approve address to use for CONNECT_ACK\n",
2356                   GNUNET_i2s (&n->id));
2357       n->state = S_DISCONNECT_FINISHED;
2358       free_neighbour (n, GNUNET_NO);
2359       return;
2360     }
2361     break;
2362   case S_CONNECT_RECV_ACK:
2363     if (0 == delay.rel_value)
2364     {
2365       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2366                   "Connection to `%s' timed out waiting for other peer to send SESSION_ACK\n",
2367                   GNUNET_i2s (&n->id));
2368       disconnect_neighbour (n);
2369       return;
2370     }
2371     break;
2372   case S_CONNECTED:
2373     if (0 == delay.rel_value)
2374     {
2375       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2376                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs\n",
2377                   GNUNET_i2s (&n->id));
2378       disconnect_neighbour (n);
2379       return;
2380     }
2381     try_transmission_to_peer (n);
2382     send_keepalive (n);
2383     break;
2384   case S_RECONNECT_ATS:
2385     if (0 == delay.rel_value)
2386     {
2387       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2388                   "Connection to `%s' timed out, waiting for ATS replacement address\n",
2389                   GNUNET_i2s (&n->id));
2390       disconnect_neighbour (n);
2391       return;
2392     }
2393     break;
2394   case S_RECONNECT_BLACKLIST:
2395     if (0 == delay.rel_value)
2396     {
2397       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2398                   "Connection to `%s' timed out, waiting for BLACKLIST to approve replacement address\n",
2399                   GNUNET_i2s (&n->id));
2400       disconnect_neighbour (n);
2401       return;
2402     }
2403     break;
2404   case S_RECONNECT_SENT:
2405     if (0 == delay.rel_value)
2406     {
2407       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2408                   "Connection to `%s' timed out, waiting for other peer to CONNECT_ACK replacement address\n",
2409                   GNUNET_i2s (&n->id));
2410       disconnect_neighbour (n);
2411       return;
2412     }
2413     break;
2414   case S_CONNECTED_SWITCHING_BLACKLIST:
2415     if (0 == delay.rel_value)
2416     {
2417       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2418                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs\n",
2419                   GNUNET_i2s (&n->id));
2420       disconnect_neighbour (n);
2421       return;
2422     }
2423     try_transmission_to_peer (n);
2424     send_keepalive (n);
2425     break;
2426   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2427     if (0 == delay.rel_value)
2428     {
2429       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2430                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs (after trying to CONNECT on alternative address)\n",
2431                   GNUNET_i2s (&n->id));
2432       disconnect_neighbour (n);
2433       return;
2434     }
2435     try_transmission_to_peer (n);
2436     send_keepalive (n);
2437     break;
2438   case S_DISCONNECT:
2439     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2440                 "Cleaning up connection to `%s' after sending DISCONNECT\n",
2441                 GNUNET_i2s (&n->id));
2442     n->state = S_DISCONNECT_FINISHED;
2443     free_neighbour (n, GNUNET_NO);
2444     return;
2445   case S_DISCONNECT_FINISHED:
2446     /* how did we get here!? */
2447     GNUNET_assert (0);
2448     break;
2449   default:
2450     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2451     GNUNET_break (0);
2452     break;  
2453   }
2454   delay = GNUNET_TIME_relative_min (GNUNET_TIME_absolute_get_remaining (n->keep_alive_time),
2455                                     delay);
2456   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == n->task);
2457   n->task = GNUNET_SCHEDULER_add_delayed (delay,
2458                                           &master_task,
2459                                           n);
2460 }
2461
2462
2463 /**
2464  * Send a SESSION_ACK message to the neighbour to confirm that we
2465  * got his CONNECT_ACK.
2466  *
2467  * @param n neighbour to send the SESSION_ACK to
2468  */
2469 static void
2470 send_session_ack_message (struct NeighbourMapEntry *n)
2471 {
2472   struct GNUNET_MessageHeader msg;
2473
2474   msg.size = htons (sizeof (struct GNUNET_MessageHeader));
2475   msg.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_ACK);
2476   (void) send_with_session(n,
2477                            (const char *) &msg, sizeof (struct GNUNET_MessageHeader),
2478                            UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_REL,
2479                            NULL, NULL);
2480 }
2481
2482
2483 /**
2484  * We received a 'SESSION_CONNECT_ACK' message from the other peer.
2485  * Consider switching to it.
2486  *
2487  * @param message possibly a 'struct SessionConnectMessage' (check format)
2488  * @param peer identity of the peer to switch the address for
2489  * @param address address of the other peer, NULL if other peer
2490  *                       connected to us
2491  * @param session session to use (or NULL)
2492  * @param ats performance data
2493  * @param ats_count number of entries in ats
2494  */
2495 void
2496 GST_neighbours_handle_connect_ack (const struct GNUNET_MessageHeader *message,
2497                                    const struct GNUNET_PeerIdentity *peer,
2498                                    const struct GNUNET_HELLO_Address *address,
2499                                    struct Session *session,
2500                                    const struct GNUNET_ATS_Information *ats,
2501                                    uint32_t ats_count)
2502 {
2503   const struct SessionConnectMessage *scm;
2504   struct GNUNET_TIME_Absolute ts;
2505   struct NeighbourMapEntry *n;
2506
2507   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2508               "Received CONNECT_ACK message from peer `%s'\n",
2509               GNUNET_i2s (peer));
2510   if (ntohs (message->size) != sizeof (struct SessionConnectMessage))
2511   {
2512     GNUNET_break_op (0);
2513     return;
2514   }
2515   scm = (const struct SessionConnectMessage *) message;
2516   GNUNET_break_op (ntohl (scm->reserved) == 0);
2517   if (NULL == (n = lookup_neighbour (peer)))
2518   {
2519     GNUNET_STATISTICS_update (GST_stats,
2520                               gettext_noop
2521                               ("# unexpected CONNECT_ACK messages (no peer)"),
2522                               1, GNUNET_NO);
2523     return;
2524   }
2525   ts = GNUNET_TIME_absolute_ntoh (scm->timestamp);
2526   switch (n->state)
2527   {
2528   case S_NOT_CONNECTED:
2529     GNUNET_break (0);
2530     free_neighbour (n, GNUNET_NO);
2531     return;
2532   case S_INIT_ATS:
2533   case S_INIT_BLACKLIST:
2534     GNUNET_STATISTICS_update (GST_stats,
2535                               gettext_noop
2536                               ("# unexpected CONNECT_ACK messages (not ready)"),
2537                               1, GNUNET_NO);
2538     break;    
2539   case S_CONNECT_SENT:
2540     if (ts.abs_value != n->primary_address.connect_timestamp.abs_value)
2541       break; /* ACK does not match our original CONNECT message */
2542     n->state = S_CONNECTED;
2543     n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2544     GNUNET_STATISTICS_set (GST_stats, 
2545                            gettext_noop ("# peers connected"), 
2546                            ++neighbours_connected,
2547                            GNUNET_NO);
2548     connect_notify_cb (callback_cls, &n->id, ats, ats_count);
2549     set_address (&n->primary_address,
2550                  n->primary_address.address,
2551                  n->primary_address.session,
2552                  n->primary_address.bandwidth_in,
2553                  n->primary_address.bandwidth_out,
2554                  GNUNET_YES);
2555     send_session_ack_message (n);
2556     break;
2557   case S_CONNECT_RECV_ATS:
2558   case S_CONNECT_RECV_BLACKLIST:
2559   case S_CONNECT_RECV_ACK:
2560     GNUNET_STATISTICS_update (GST_stats,
2561                               gettext_noop
2562                               ("# unexpected CONNECT_ACK messages (not ready)"),
2563                               1, GNUNET_NO);
2564     break;
2565   case S_CONNECTED:
2566     /* duplicate CONNECT_ACK, let's answer by duplciate SESSION_ACK just in case */
2567     send_session_ack_message (n);
2568     break;
2569   case S_RECONNECT_ATS:
2570   case S_RECONNECT_BLACKLIST:
2571     /* we didn't expect any CONNECT_ACK, as we are waiting for ATS
2572        to give us a new address... */
2573     GNUNET_STATISTICS_update (GST_stats,
2574                               gettext_noop
2575                               ("# unexpected CONNECT_ACK messages (waiting on ATS)"),
2576                               1, GNUNET_NO);
2577     break;
2578   case S_RECONNECT_SENT:
2579     /* new address worked; go back to connected! */
2580     n->state = S_CONNECTED;
2581     send_session_ack_message (n);
2582     break;
2583   case S_CONNECTED_SWITCHING_BLACKLIST:
2584     /* duplicate CONNECT_ACK, let's answer by duplciate SESSION_ACK just in case */
2585     send_session_ack_message (n);
2586     break;
2587   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2588     /* new address worked; adopt it and go back to connected! */
2589     n->state = S_CONNECTED;
2590     n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2591     GNUNET_break (GNUNET_NO == n->alternative_address.ats_active);
2592     set_address (&n->primary_address,
2593                  n->alternative_address.address,
2594                  n->alternative_address.session,
2595                  n->alternative_address.bandwidth_in,
2596                  n->alternative_address.bandwidth_out,
2597                  GNUNET_YES);
2598     free_address (&n->alternative_address);
2599     send_session_ack_message (n);
2600     break;    
2601   case S_DISCONNECT:
2602     GNUNET_STATISTICS_update (GST_stats,
2603                               gettext_noop
2604                               ("# unexpected CONNECT_ACK messages (disconnecting)"),
2605                               1, GNUNET_NO);
2606     break;
2607   case S_DISCONNECT_FINISHED:
2608     GNUNET_assert (0);
2609     break;
2610   default:
2611     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2612     GNUNET_break (0);
2613     break;   
2614   }
2615 }
2616
2617
2618 /**
2619  * A session was terminated. Take note; if needed, try to get
2620  * an alternative address from ATS.
2621  *
2622  * @param peer identity of the peer where the session died
2623  * @param session session that is gone
2624  */
2625 void
2626 GST_neighbours_session_terminated (const struct GNUNET_PeerIdentity *peer,
2627                                    struct Session *session)
2628 {
2629   struct NeighbourMapEntry *n;
2630   struct BlackListCheckContext *bcc;
2631   struct BlackListCheckContext *bcc_next;
2632
2633   /* make sure to cancel all ongoing blacklist checks involving 'session' */
2634   bcc_next = bc_head;
2635   while (NULL != (bcc = bcc_next))
2636   {
2637     bcc_next = bcc->next;
2638     if (bcc->na.session == session)
2639     {
2640       GST_blacklist_test_cancel (bcc->bc);
2641       GNUNET_HELLO_address_free (bcc->na.address);
2642       GNUNET_CONTAINER_DLL_remove (bc_head,
2643                                    bc_tail,
2644                                    bcc);
2645       GNUNET_free (bcc);
2646     }
2647   }
2648   if (NULL == (n = lookup_neighbour (peer)))
2649     return; /* can't affect us */
2650   if (session != n->primary_address.session)
2651   {
2652     if (session == n->alternative_address.session)
2653     {
2654       free_address (&n->alternative_address);
2655       if ( (S_CONNECTED_SWITCHING_BLACKLIST == n->state) ||
2656            (S_CONNECTED_SWITCHING_CONNECT_SENT == n->state) )
2657         n->state = S_CONNECTED;
2658       else
2659         GNUNET_break (0);
2660     }
2661     return; /* doesn't affect us further */
2662   }
2663
2664   n->expect_latency_response = GNUNET_NO;
2665
2666   switch (n->state)
2667   {
2668   case S_NOT_CONNECTED:
2669     GNUNET_break (0);
2670     free_neighbour (n, GNUNET_NO);
2671     return;
2672   case S_INIT_ATS:
2673     GNUNET_break (0);
2674     free_neighbour (n, GNUNET_NO);
2675     return;
2676   case S_INIT_BLACKLIST:
2677   case S_CONNECT_SENT:
2678     free_address (&n->primary_address);
2679     n->state = S_INIT_ATS;
2680     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
2681     // FIXME: need to ask ATS for suggestions again?
2682     GNUNET_ATS_suggest_address (GST_ats, &n->id);
2683     break;
2684   case S_CONNECT_RECV_ATS:    
2685   case S_CONNECT_RECV_BLACKLIST:
2686   case S_CONNECT_RECV_ACK:
2687     /* error on inbound session; free neighbour entirely */
2688     free_address (&n->primary_address);
2689     free_neighbour (n, GNUNET_NO);
2690     return;
2691   case S_CONNECTED:
2692     free_address (&n->primary_address);
2693     n->state = S_RECONNECT_ATS;
2694     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
2695     /* FIXME: is this ATS call needed? */
2696     GNUNET_ATS_suggest_address (GST_ats, &n->id);
2697     break;
2698   case S_RECONNECT_ATS:
2699     /* we don't have an address, how can it go down? */
2700     GNUNET_break (0);
2701     break;
2702   case S_RECONNECT_BLACKLIST:
2703   case S_RECONNECT_SENT:
2704     n->state = S_RECONNECT_ATS;
2705     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
2706     // FIXME: need to ask ATS for suggestions again?
2707     GNUNET_ATS_suggest_address (GST_ats, &n->id);
2708     break;
2709   case S_CONNECTED_SWITCHING_BLACKLIST:
2710     /* primary went down while we were checking secondary against
2711        blacklist, adopt secondary as primary */       
2712     free_address (&n->primary_address);
2713     n->primary_address = n->alternative_address;
2714     memset (&n->alternative_address, 0, sizeof (struct NeighbourAddress));
2715     n->timeout = GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT);
2716     n->state = S_RECONNECT_BLACKLIST;
2717     break;
2718   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2719     /* primary went down while we were waiting for CONNECT_ACK on secondary;
2720        secondary as primary */       
2721     free_address (&n->primary_address);
2722     n->primary_address = n->alternative_address;
2723     memset (&n->alternative_address, 0, sizeof (struct NeighbourAddress));
2724     n->timeout = GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT);
2725     n->state = S_RECONNECT_SENT;
2726     break;
2727   case S_DISCONNECT:
2728     free_address (&n->primary_address);
2729     break;
2730   case S_DISCONNECT_FINISHED:
2731     /* neighbour was freed and plugins told to terminate session */
2732     break;
2733   default:
2734     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2735     GNUNET_break (0);
2736     break;
2737   }
2738   if (GNUNET_SCHEDULER_NO_TASK != n->task)
2739     GNUNET_SCHEDULER_cancel (n->task);
2740   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
2741 }
2742
2743
2744 /**
2745  * We received a 'SESSION_ACK' message from the other peer.
2746  * If we sent a 'CONNECT_ACK' last, this means we are now
2747  * connected.  Otherwise, do nothing.
2748  *
2749  * @param message possibly a 'struct SessionConnectMessage' (check format)
2750  * @param peer identity of the peer to switch the address for
2751  * @param address address of the other peer, NULL if other peer
2752  *                       connected to us
2753  * @param session session to use (or NULL)
2754  * @param ats performance data
2755  * @param ats_count number of entries in ats
2756  */
2757 void
2758 GST_neighbours_handle_session_ack (const struct GNUNET_MessageHeader *message,
2759                                    const struct GNUNET_PeerIdentity *peer,
2760                                    const struct GNUNET_HELLO_Address *address,
2761                                    struct Session *session,
2762                                    const struct GNUNET_ATS_Information *ats,
2763                                    uint32_t ats_count)
2764 {
2765   struct NeighbourMapEntry *n;
2766
2767   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
2768               "Received SESSION_ACK message from peer `%s'\n",
2769               GNUNET_i2s (peer));
2770   if (ntohs (message->size) != sizeof (struct GNUNET_MessageHeader))
2771   {
2772     GNUNET_break_op (0);
2773     return;
2774   }
2775   if (NULL == (n = lookup_neighbour (peer)))
2776     return;
2777   /* check if we are in a plausible state for having sent
2778      a CONNECT_ACK.  If not, return, otherwise break */
2779   if ( ( (S_CONNECT_RECV_ACK != n->state) &&
2780          (S_CONNECT_SENT != n->state) ) ||
2781        (2 != n->send_connect_ack) )
2782   {
2783     GNUNET_STATISTICS_update (GST_stats,
2784                               gettext_noop ("# unexpected SESSION ACK messages"), 1,
2785                               GNUNET_NO);
2786     return;
2787   }
2788   n->state = S_CONNECTED;
2789   n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2790   GNUNET_STATISTICS_set (GST_stats, 
2791                          gettext_noop ("# peers connected"), 
2792                          ++neighbours_connected,
2793                          GNUNET_NO);
2794   connect_notify_cb (callback_cls, &n->id, ats, ats_count);
2795   set_address (&n->primary_address,
2796                n->primary_address.address,
2797                n->primary_address.session,
2798                n->primary_address.bandwidth_in,
2799                n->primary_address.bandwidth_out,
2800                GNUNET_YES);
2801 }
2802
2803
2804 /**
2805  * Test if we're connected to the given peer.
2806  *
2807  * @param target peer to test
2808  * @return GNUNET_YES if we are connected, GNUNET_NO if not
2809  */
2810 int
2811 GST_neighbours_test_connected (const struct GNUNET_PeerIdentity *target)
2812 {
2813   return test_connected (lookup_neighbour (target));
2814 }
2815
2816
2817 /**
2818  * Change the incoming quota for the given peer.
2819  *
2820  * @param neighbour identity of peer to change qutoa for
2821  * @param quota new quota
2822  */
2823 void
2824 GST_neighbours_set_incoming_quota (const struct GNUNET_PeerIdentity *neighbour,
2825                                    struct GNUNET_BANDWIDTH_Value32NBO quota)
2826 {
2827   struct NeighbourMapEntry *n;
2828
2829   if (NULL == (n = lookup_neighbour (neighbour)))
2830   {
2831     GNUNET_STATISTICS_update (GST_stats,
2832                               gettext_noop
2833                               ("# SET QUOTA messages ignored (no such peer)"),
2834                               1, GNUNET_NO);
2835     return;
2836   }
2837   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2838               "Setting inbound quota of %u Bps for peer `%s' to all clients\n",
2839               ntohl (quota.value__), GNUNET_i2s (&n->id));
2840   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker, quota);
2841   if (0 != ntohl (quota.value__))
2842     return;
2843   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting peer `%4s' due to `%s'\n",
2844               GNUNET_i2s (&n->id), "SET_QUOTA");
2845   if (GNUNET_YES == test_connected (n))
2846     GNUNET_STATISTICS_update (GST_stats,
2847                               gettext_noop ("# disconnects due to quota of 0"),
2848                               1, GNUNET_NO);
2849   disconnect_neighbour (n);
2850 }
2851
2852
2853 /**
2854  * We received a disconnect message from the given peer,
2855  * validate and process.
2856  *
2857  * @param peer sender of the message
2858  * @param msg the disconnect message
2859  */
2860 void
2861 GST_neighbours_handle_disconnect_message (const struct GNUNET_PeerIdentity
2862                                           *peer,
2863                                           const struct GNUNET_MessageHeader
2864                                           *msg)
2865 {
2866   struct NeighbourMapEntry *n;
2867   const struct SessionDisconnectMessage *sdm;
2868   GNUNET_HashCode hc;
2869
2870   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2871               "Received DISCONNECT message from peer `%s'\n",
2872               GNUNET_i2s (peer));
2873   if (ntohs (msg->size) != sizeof (struct SessionDisconnectMessage))
2874   {
2875     // GNUNET_break_op (0);
2876     GNUNET_STATISTICS_update (GST_stats,
2877                               gettext_noop
2878                               ("# disconnect messages ignored (old format)"), 1,
2879                               GNUNET_NO);
2880     return;
2881   }
2882   sdm = (const struct SessionDisconnectMessage *) msg;
2883   if (NULL == (n = lookup_neighbour (peer)))
2884     return;                     /* gone already */
2885   if (GNUNET_TIME_absolute_ntoh (sdm->timestamp).abs_value <= n->connect_ack_timestamp.abs_value)
2886   {
2887     GNUNET_STATISTICS_update (GST_stats,
2888                               gettext_noop
2889                               ("# disconnect messages ignored (timestamp)"), 1,
2890                               GNUNET_NO);
2891     return;
2892   }
2893   GNUNET_CRYPTO_hash (&sdm->public_key,
2894                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2895                       &hc);
2896   if (0 != memcmp (peer, &hc, sizeof (struct GNUNET_PeerIdentity)))
2897   {
2898     GNUNET_break_op (0);
2899     return;
2900   }
2901   if (ntohl (sdm->purpose.size) !=
2902       sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
2903       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
2904       sizeof (struct GNUNET_TIME_AbsoluteNBO))
2905   {
2906     GNUNET_break_op (0);
2907     return;
2908   }
2909   if (GNUNET_OK !=
2910       GNUNET_CRYPTO_rsa_verify
2911       (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT, &sdm->purpose,
2912        &sdm->signature, &sdm->public_key))
2913   {
2914     GNUNET_break_op (0);
2915     return;
2916   }
2917   if (GNUNET_YES == test_connected (n))
2918     GNUNET_STATISTICS_update (GST_stats,
2919                               gettext_noop
2920                               ("# other peer asked to disconnect from us"), 1,
2921                               GNUNET_NO);
2922   disconnect_neighbour (n);
2923 }
2924
2925
2926 /**
2927  * Closure for the neighbours_iterate function.
2928  */
2929 struct IteratorContext
2930 {
2931   /**
2932    * Function to call on each connected neighbour.
2933    */
2934   GST_NeighbourIterator cb;
2935
2936   /**
2937    * Closure for 'cb'.
2938    */
2939   void *cb_cls;
2940 };
2941
2942
2943 /**
2944  * Call the callback from the closure for each connected neighbour.
2945  *
2946  * @param cls the 'struct IteratorContext'
2947  * @param key the hash of the public key of the neighbour
2948  * @param value the 'struct NeighbourMapEntry'
2949  * @return GNUNET_OK (continue to iterate)
2950  */
2951 static int
2952 neighbours_iterate (void *cls, const GNUNET_HashCode * key, void *value)
2953 {
2954   struct IteratorContext *ic = cls;
2955   struct NeighbourMapEntry *n = value;
2956
2957   if (GNUNET_YES == test_connected (n))
2958     ic->cb (ic->cb_cls, &n->id, NULL, 0, n->primary_address.address);
2959   return GNUNET_OK;
2960 }
2961
2962
2963 /**
2964  * Iterate over all connected neighbours.
2965  *
2966  * @param cb function to call
2967  * @param cb_cls closure for cb
2968  */
2969 void
2970 GST_neighbours_iterate (GST_NeighbourIterator cb, void *cb_cls)
2971 {
2972   struct IteratorContext ic;
2973
2974   if (NULL == neighbours)  
2975     return; /* can happen during shutdown */
2976   ic.cb = cb;
2977   ic.cb_cls = cb_cls;
2978   GNUNET_CONTAINER_multihashmap_iterate (neighbours, &neighbours_iterate, &ic);
2979 }
2980
2981
2982 /**
2983  * If we have an active connection to the given target, it must be shutdown.
2984  *
2985  * @param target peer to disconnect from
2986  */
2987 void
2988 GST_neighbours_force_disconnect (const struct GNUNET_PeerIdentity *target)
2989 {
2990   struct NeighbourMapEntry *n;
2991
2992   if (NULL == (n = lookup_neighbour (target)))
2993     return;  /* not active */
2994   if (GNUNET_YES == test_connected (n))
2995     GNUNET_STATISTICS_update (GST_stats,
2996                               gettext_noop
2997                               ("# disconnected from peer upon explicit request"), 1,
2998                               GNUNET_NO);
2999   disconnect_neighbour (n);
3000 }
3001
3002
3003 /**
3004  * Obtain current latency information for the given neighbour.
3005  *
3006  * @param peer to get the latency for
3007  * @return observed latency of the address, FOREVER if the 
3008  *         the connection is not up
3009  */
3010 struct GNUNET_TIME_Relative
3011 GST_neighbour_get_latency (const struct GNUNET_PeerIdentity *peer)
3012 {
3013   struct NeighbourMapEntry *n;
3014
3015   n = lookup_neighbour (peer);
3016   if (NULL == n) 
3017     return GNUNET_TIME_UNIT_FOREVER_REL;
3018   switch (n->state)
3019   {
3020   case S_CONNECTED:
3021   case S_RECONNECT_SENT:
3022   case S_RECONNECT_ATS:
3023     return n->latency;
3024   case S_NOT_CONNECTED:
3025   case S_INIT_BLACKLIST:
3026   case S_INIT_ATS:
3027   case S_CONNECT_SENT:
3028   case S_CONNECT_RECV_BLACKLIST:
3029   case S_DISCONNECT:
3030   case S_DISCONNECT_FINISHED:
3031     return GNUNET_TIME_UNIT_FOREVER_REL;
3032   default:
3033     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
3034     GNUNET_break (0);
3035     break;
3036   }
3037   return GNUNET_TIME_UNIT_FOREVER_REL;   
3038 }
3039
3040
3041 /**
3042  * Obtain current address information for the given neighbour.
3043  *
3044  * @param peer
3045  * @return address currently used
3046  */
3047 struct GNUNET_HELLO_Address *
3048 GST_neighbour_get_current_address (const struct GNUNET_PeerIdentity *peer)
3049 {
3050   struct NeighbourMapEntry *n;
3051
3052   n = lookup_neighbour (peer);
3053   if (NULL == n)
3054     return NULL;
3055   return n->primary_address.address;
3056 }
3057
3058
3059 /**
3060  * Initialize the neighbours subsystem.
3061  *
3062  * @param cls closure for callbacks
3063  * @param connect_cb function to call if we connect to a peer
3064  * @param disconnect_cb function to call if we disconnect from a peer
3065  * @param peer_address_cb function to call if we change an active address
3066  *                   of a neighbour
3067  */
3068 void
3069 GST_neighbours_start (void *cls,
3070                       GNUNET_TRANSPORT_NotifyConnect connect_cb,
3071                       GNUNET_TRANSPORT_NotifyDisconnect disconnect_cb,
3072                       GNUNET_TRANSPORT_PeerIterateCallback peer_address_cb)
3073 {
3074   callback_cls = cls;
3075   connect_notify_cb = connect_cb;
3076   disconnect_notify_cb = disconnect_cb;
3077   address_change_cb = peer_address_cb;
3078   neighbours = GNUNET_CONTAINER_multihashmap_create (NEIGHBOUR_TABLE_SIZE);
3079 }
3080
3081
3082 /**
3083  * Disconnect from the given neighbour.
3084  *
3085  * @param cls unused
3086  * @param key hash of neighbour's public key (not used)
3087  * @param value the 'struct NeighbourMapEntry' of the neighbour
3088  * @return GNUNET_OK (continue to iterate)
3089  */
3090 static int
3091 disconnect_all_neighbours (void *cls, const GNUNET_HashCode * key, void *value)
3092 {
3093   struct NeighbourMapEntry *n = value;
3094
3095   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
3096               "Disconnecting peer `%4s', %s\n",
3097               GNUNET_i2s (&n->id), "SHUTDOWN_TASK");
3098   n->state = S_DISCONNECT_FINISHED;
3099   free_neighbour (n, GNUNET_NO);
3100   return GNUNET_OK;
3101 }
3102
3103
3104 /**
3105  * Cleanup the neighbours subsystem.
3106  */
3107 void
3108 GST_neighbours_stop ()
3109 {
3110   if (NULL == neighbours)
3111     return;
3112   GNUNET_CONTAINER_multihashmap_iterate (neighbours, 
3113                                          &disconnect_all_neighbours,
3114                                          NULL);
3115   GNUNET_CONTAINER_multihashmap_destroy (neighbours);
3116   neighbours = NULL;
3117   callback_cls = NULL;
3118   connect_notify_cb = NULL;
3119   disconnect_notify_cb = NULL;
3120   address_change_cb = NULL;
3121 }
3122
3123
3124 /* end of file gnunet-service-transport_neighbours.c */