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