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