-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, "Unhandled state `%s' \n",print_state (n->state));
1151     GNUNET_break (0);
1152     break;
1153   }
1154   /* schedule timeout to clean up */
1155   if (GNUNET_SCHEDULER_NO_TASK != n->task)
1156     GNUNET_SCHEDULER_cancel (n->task);
1157   n->task = GNUNET_SCHEDULER_add_delayed (DISCONNECT_SENT_TIMEOUT,
1158                                           &master_task, n);
1159 }
1160
1161
1162 /**
1163  * We're done with our transmission attempt, continue processing.
1164  *
1165  * @param cls the 'struct MessageQueue' of the message
1166  * @param receiver intended receiver
1167  * @param success whether it worked or not
1168  * @param size_payload bytes payload sent
1169  * @param physical bytes sent on wire
1170  */
1171 static void
1172 transmit_send_continuation (void *cls,
1173                             const struct GNUNET_PeerIdentity *receiver,
1174                             int success, size_t size_payload, size_t physical)
1175 {
1176   struct MessageQueue *mq = cls;
1177   struct NeighbourMapEntry *n;
1178
1179   if (NULL == (n = lookup_neighbour (receiver)))
1180   {
1181     GNUNET_free (mq);
1182     return; /* disconnect or other error while transmitting, can happen */
1183   }
1184   if (n->is_active == mq)
1185   {
1186     /* this is still "our" neighbour, remove us from its queue
1187        and allow it to send the next message now */
1188     n->is_active = NULL;
1189     if (GNUNET_SCHEDULER_NO_TASK != n->task)
1190       GNUNET_SCHEDULER_cancel (n->task);
1191     n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
1192   }
1193   if (bytes_in_send_queue < mq->message_buf_size)
1194   {
1195       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1196                   "Bytes_in_send_queue `%u', Message_size %u, result: %s, payload %u, on wire %u\n",
1197                   bytes_in_send_queue, mq->message_buf_size,
1198                   (GNUNET_OK == success) ? "OK" : "FAIL",
1199                   size_payload, physical);
1200       GNUNET_break (0);
1201   }
1202
1203
1204   GNUNET_break (size_payload == mq->message_buf_size);
1205   bytes_in_send_queue -= mq->message_buf_size;
1206   GNUNET_STATISTICS_set (GST_stats,
1207                         gettext_noop
1208                          ("# bytes in message queue for other peers"),
1209                          bytes_in_send_queue, GNUNET_NO);
1210   if (GNUNET_OK == success)
1211     GNUNET_STATISTICS_update (GST_stats,
1212                               gettext_noop
1213                               ("# messages transmitted to other peers"),
1214                               1, GNUNET_NO);
1215   else
1216     GNUNET_STATISTICS_update (GST_stats,
1217                               gettext_noop
1218                               ("# transmission failures for messages to other peers"),
1219                               1, GNUNET_NO);
1220   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1221               "Sending message to `%s' of type %u was a %s\n",
1222               GNUNET_i2s (receiver),
1223               ntohs (((struct GNUNET_MessageHeader *) mq->message_buf)->type),
1224               (success == GNUNET_OK) ? "success" : "FAILURE");
1225   if (NULL != mq->cont)
1226     mq->cont (mq->cont_cls, success, size_payload, physical);
1227   GNUNET_free (mq);
1228 }
1229
1230
1231 /**
1232  * Check the message list for the given neighbour and if we can
1233  * send a message, do so.  This function should only be called
1234  * if the connection is at least generally ready for transmission.
1235  * While we will only send one message at a time, no bandwidth
1236  * quota management is performed here.  If a message was given to
1237  * the plugin, the continuation will automatically re-schedule
1238  * the 'master' task once the next message might be transmitted.
1239  *
1240  * @param n target peer for which to transmit
1241  */
1242 static void
1243 try_transmission_to_peer (struct NeighbourMapEntry *n)
1244 {
1245   struct MessageQueue *mq;
1246   struct GNUNET_TIME_Relative timeout;
1247
1248   if (NULL == n->primary_address.address)
1249   {
1250     /* no address, why are we here? */
1251     GNUNET_break (0);
1252     return;
1253   }
1254   if ((0 == n->primary_address.address->address_length) &&
1255       (NULL == n->primary_address.session))
1256   {
1257     /* no address, why are we here? */
1258     GNUNET_break (0);
1259     return;
1260   }
1261   if (NULL != n->is_active)
1262   {
1263     /* transmission already pending */
1264     return;
1265   }
1266
1267   /* timeout messages from the queue that are past their due date */
1268   while (NULL != (mq = n->messages_head))
1269   {
1270     timeout = GNUNET_TIME_absolute_get_remaining (mq->timeout);
1271     if (timeout.rel_value_us > 0)
1272       break;
1273     GNUNET_STATISTICS_update (GST_stats,
1274                               gettext_noop
1275                               ("# messages timed out while in transport queue"),
1276                               1, GNUNET_NO);
1277     GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
1278     n->is_active = mq;
1279     transmit_send_continuation (mq, &n->id, GNUNET_SYSERR, mq->message_buf_size, 0);     /* timeout */
1280   }
1281   if (NULL == mq)
1282     return;                     /* no more messages */
1283   GNUNET_CONTAINER_DLL_remove (n->messages_head, n->messages_tail, mq);
1284   n->is_active = mq;
1285   send_with_session (n,
1286                      mq->message_buf, mq->message_buf_size,
1287                      0 /* priority */, timeout,
1288                      &transmit_send_continuation, mq);
1289 }
1290
1291
1292 /**
1293  * Send keepalive message to the neighbour.  Must only be called
1294  * if we are on 'connected' state or while trying to switch addresses.
1295  * Will internally determine if a keepalive is truly needed (so can
1296  * always be called).
1297  *
1298  * @param n neighbour that went idle and needs a keepalive
1299  */
1300 static void
1301 send_keepalive (struct NeighbourMapEntry *n)
1302 {
1303   struct GNUNET_MessageHeader m;
1304
1305   GNUNET_assert ((S_CONNECTED == n->state) ||
1306                  (S_CONNECTED_SWITCHING_BLACKLIST == n->state) ||
1307                  (S_CONNECTED_SWITCHING_CONNECT_SENT));
1308   if (GNUNET_TIME_absolute_get_remaining (n->keep_alive_time).rel_value_us > 0)
1309     return; /* no keepalive needed at this time */
1310   m.size = htons (sizeof (struct GNUNET_MessageHeader));
1311   m.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE);
1312   send_with_session (n,
1313                      (const void *) &m, sizeof (m),
1314                      UINT32_MAX /* priority */,
1315                      KEEPALIVE_FREQUENCY,
1316                      NULL, NULL);
1317   GNUNET_STATISTICS_update (GST_stats, gettext_noop ("# keepalives sent"), 1,
1318                             GNUNET_NO);
1319   n->expect_latency_response = GNUNET_YES;
1320   n->last_keep_alive_time = GNUNET_TIME_absolute_get ();
1321   n->keep_alive_time = GNUNET_TIME_relative_to_absolute (KEEPALIVE_FREQUENCY);
1322 }
1323
1324
1325 /**
1326  * Keep the connection to the given neighbour alive longer,
1327  * we received a KEEPALIVE (or equivalent); send a response.
1328  *
1329  * @param neighbour neighbour to keep alive (by sending keep alive response)
1330  */
1331 void
1332 GST_neighbours_keepalive (const struct GNUNET_PeerIdentity *neighbour)
1333 {
1334   struct NeighbourMapEntry *n;
1335   struct GNUNET_MessageHeader m;
1336
1337   if (NULL == (n = lookup_neighbour (neighbour)))
1338   {
1339     GNUNET_STATISTICS_update (GST_stats,
1340                               gettext_noop
1341                               ("# KEEPALIVE messages discarded (peer unknown)"),
1342                               1, GNUNET_NO);
1343     return;
1344   }
1345   if (NULL == n->primary_address.session)
1346   {
1347     GNUNET_STATISTICS_update (GST_stats,
1348                               gettext_noop
1349                               ("# KEEPALIVE messages discarded (no session)"),
1350                               1, GNUNET_NO);
1351     return;
1352   }
1353   /* send reply to allow neighbour to measure latency */
1354   m.size = htons (sizeof (struct GNUNET_MessageHeader));
1355   m.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_KEEPALIVE_RESPONSE);
1356   send_with_session(n,
1357                     (const void *) &m, sizeof (m),
1358                     UINT32_MAX /* priority */,
1359                     KEEPALIVE_FREQUENCY,
1360                     NULL, NULL);
1361 }
1362
1363
1364 /**
1365  * We received a KEEP_ALIVE_RESPONSE message and use this to calculate
1366  * latency to this peer.  Pass the updated information (existing ats
1367  * plus calculated latency) to ATS.
1368  *
1369  * @param neighbour neighbour to keep alive
1370  */
1371 void
1372 GST_neighbours_keepalive_response (const struct GNUNET_PeerIdentity *neighbour)
1373 {
1374   struct NeighbourMapEntry *n;
1375   uint32_t latency;
1376   struct GNUNET_ATS_Information ats;
1377
1378   if (NULL == (n = lookup_neighbour (neighbour)))
1379   {
1380     GNUNET_STATISTICS_update (GST_stats,
1381                               gettext_noop
1382                               ("# KEEPALIVE_RESPONSE messages discarded (not connected)"),
1383                               1, GNUNET_NO);
1384     return;
1385   }
1386   if ( (S_CONNECTED != n->state) ||
1387        (GNUNET_YES != n->expect_latency_response) )
1388   {
1389     GNUNET_STATISTICS_update (GST_stats,
1390                               gettext_noop
1391                               ("# KEEPALIVE_RESPONSE messages discarded (not expected)"),
1392                               1, GNUNET_NO);
1393     return;
1394   }
1395   n->expect_latency_response = GNUNET_NO;
1396   n->latency = GNUNET_TIME_absolute_get_duration (n->last_keep_alive_time);
1397   n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1398   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1399               "Latency for peer `%s' is %s\n",
1400               GNUNET_i2s (&n->id),
1401               GNUNET_STRINGS_relative_time_to_string (n->latency,
1402                                                       GNUNET_YES));
1403   /* append latency */
1404   ats.type = htonl (GNUNET_ATS_QUALITY_NET_DELAY);
1405   if (n->latency.rel_value_us > UINT32_MAX)
1406     latency = UINT32_MAX;
1407   else
1408     latency = n->latency.rel_value_us;
1409   ats.value = htonl (latency);
1410   GST_ats_update_metrics (&n->id,
1411                                                                                           n->primary_address.address,
1412                                                                                         n->primary_address.session,
1413                                                                                         &ats, 1);
1414 }
1415
1416
1417 /**
1418  * We have received a message from the given sender.  How long should
1419  * we delay before receiving more?  (Also used to keep the peer marked
1420  * as live).
1421  *
1422  * @param sender sender of the message
1423  * @param size size of the message
1424  * @param do_forward set to GNUNET_YES if the message should be forwarded to clients
1425  *                   GNUNET_NO if the neighbour is not connected or violates the quota,
1426  *                   GNUNET_SYSERR if the connection is not fully up yet
1427  * @return how long to wait before reading more from this sender
1428  */
1429 struct GNUNET_TIME_Relative
1430 GST_neighbours_calculate_receive_delay (const struct GNUNET_PeerIdentity
1431                                         *sender, ssize_t size, int *do_forward)
1432 {
1433   struct NeighbourMapEntry *n;
1434   struct GNUNET_TIME_Relative ret;
1435
1436   if (NULL == neighbours)
1437   {
1438     *do_forward = GNUNET_NO;
1439     return GNUNET_TIME_UNIT_FOREVER_REL; /* This can happen during shutdown */
1440   }
1441   if (NULL == (n = lookup_neighbour (sender)))
1442   {
1443     GST_neighbours_try_connect (sender);
1444     if (NULL == (n = lookup_neighbour (sender)))
1445     {
1446       GNUNET_STATISTICS_update (GST_stats,
1447                                 gettext_noop
1448                                 ("# messages discarded due to lack of neighbour record"),
1449                                 1, GNUNET_NO);
1450       *do_forward = GNUNET_NO;
1451       return GNUNET_TIME_UNIT_ZERO;
1452     }
1453   }
1454   if (! test_connected (n))
1455   {
1456     *do_forward = GNUNET_SYSERR;
1457     return GNUNET_TIME_UNIT_ZERO;
1458   }
1459   if (GNUNET_YES == GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, size))
1460   {
1461     n->quota_violation_count++;
1462     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1463                 "Bandwidth quota (%u b/s) violation detected (total of %u).\n",
1464                 n->in_tracker.available_bytes_per_s__,
1465                 n->quota_violation_count);
1466     /* Discount 32k per violation */
1467     GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, -32 * 1024);
1468   }
1469   else
1470   {
1471     if (n->quota_violation_count > 0)
1472     {
1473       /* try to add 32k back */
1474       GNUNET_BANDWIDTH_tracker_consume (&n->in_tracker, 32 * 1024);
1475       n->quota_violation_count--;
1476     }
1477   }
1478   if (n->quota_violation_count > QUOTA_VIOLATION_DROP_THRESHOLD)
1479   {
1480     GNUNET_STATISTICS_update (GST_stats,
1481                               gettext_noop
1482                               ("# bandwidth quota violations by other peers"),
1483                               1, GNUNET_NO);
1484     *do_forward = GNUNET_NO;
1485     return GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT;
1486   }
1487   *do_forward = GNUNET_YES;
1488   ret = GNUNET_BANDWIDTH_tracker_get_delay (&n->in_tracker, 32 * 1024);
1489   if (ret.rel_value_us > 0)
1490   {
1491     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1492                 "Throttling read (%llu bytes excess at %u b/s), waiting %s before reading more.\n",
1493                 (unsigned long long) n->in_tracker.
1494                 consumption_since_last_update__,
1495                 (unsigned int) n->in_tracker.available_bytes_per_s__,
1496                 GNUNET_STRINGS_relative_time_to_string (ret, GNUNET_YES));
1497     GNUNET_STATISTICS_update (GST_stats,
1498                               gettext_noop ("# ms throttling suggested"),
1499                               (int64_t) ret.rel_value_us / 1000LL,
1500                               GNUNET_NO);
1501   }
1502   return ret;
1503 }
1504
1505
1506 /**
1507  * Transmit a message to the given target using the active connection.
1508  *
1509  * @param target destination
1510  * @param msg message to send
1511  * @param msg_size number of bytes in msg
1512  * @param timeout when to fail with timeout
1513  * @param cont function to call when done
1514  * @param cont_cls closure for 'cont'
1515  */
1516 void
1517 GST_neighbours_send (const struct GNUNET_PeerIdentity *target, const void *msg,
1518                      size_t msg_size, struct GNUNET_TIME_Relative timeout,
1519                      GST_NeighbourSendContinuation cont, void *cont_cls)
1520 {
1521   struct NeighbourMapEntry *n;
1522   struct MessageQueue *mq;
1523
1524   /* All ove these cases should never happen; they are all API violations.
1525      But we check anyway, just to be sure. */
1526   if (NULL == (n = lookup_neighbour (target)))
1527   {
1528     GNUNET_break (0);
1529     if (NULL != cont)
1530       cont (cont_cls, GNUNET_SYSERR, msg_size, 0);
1531     return;
1532   }
1533   if (GNUNET_YES != test_connected (n))
1534   {
1535     GNUNET_break (0);
1536     if (NULL != cont)
1537       cont (cont_cls, GNUNET_SYSERR, msg_size, 0);
1538     return;
1539   }
1540   bytes_in_send_queue += msg_size;
1541   GNUNET_STATISTICS_set (GST_stats,
1542                          gettext_noop
1543                          ("# bytes in message queue for other peers"),
1544                          bytes_in_send_queue, GNUNET_NO);
1545   mq = GNUNET_malloc (sizeof (struct MessageQueue) + msg_size);
1546   mq->cont = cont;
1547   mq->cont_cls = cont_cls;
1548   memcpy (&mq[1], msg, msg_size);
1549   mq->message_buf = (const char *) &mq[1];
1550   mq->message_buf_size = msg_size;
1551   mq->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1552   GNUNET_CONTAINER_DLL_insert_tail (n->messages_head, n->messages_tail, mq);
1553   if ( (NULL != n->is_active) ||
1554        ( (NULL == n->primary_address.session) && (NULL == n->primary_address.address)) )
1555     return;
1556   if (GNUNET_SCHEDULER_NO_TASK != n->task)
1557     GNUNET_SCHEDULER_cancel (n->task);
1558   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
1559 }
1560
1561
1562 /**
1563  * Send a SESSION_CONNECT message via the given address.
1564  *
1565  * @param na address to use
1566  */
1567 static void
1568 send_session_connect (struct NeighbourAddress *na)
1569 {
1570   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1571   struct SessionConnectMessage connect_msg;
1572
1573   if (NULL == (papi = GST_plugins_find (na->address->transport_name)))
1574   {
1575     GNUNET_break (0);
1576     return;
1577   }
1578   if (NULL == na->session)
1579     na->session = papi->get_session (papi->cls, na->address);
1580   if (NULL == na->session)
1581   {
1582     GNUNET_break (0);
1583     return;
1584   }
1585   na->connect_timestamp = GNUNET_TIME_absolute_get ();
1586   connect_msg.header.size = htons (sizeof (struct SessionConnectMessage));
1587   connect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT);
1588   connect_msg.reserved = htonl (0);
1589   connect_msg.timestamp = GNUNET_TIME_absolute_hton (na->connect_timestamp);
1590   (void) papi->send (papi->cls,
1591                      na->session,
1592                      (const char *) &connect_msg, sizeof (struct SessionConnectMessage),
1593                      UINT_MAX,
1594                      GNUNET_TIME_UNIT_FOREVER_REL,
1595                      NULL, NULL);
1596   GST_neighbours_notify_data_sent (&na->address->peer,
1597       na->address, na->session, sizeof (struct SessionConnectMessage));
1598
1599 }
1600
1601
1602 /**
1603  * Send a SESSION_CONNECT_ACK message via the given address.
1604  *
1605  * @param address address to use
1606  * @param session session to use
1607  * @param timestamp timestamp to use for the ACK message
1608  */
1609 static void
1610 send_session_connect_ack_message (const struct GNUNET_HELLO_Address *address,
1611                                   struct Session *session,
1612                                   struct GNUNET_TIME_Absolute timestamp)
1613 {
1614   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1615   struct SessionConnectMessage connect_msg;
1616
1617   if (NULL == (papi = GST_plugins_find (address->transport_name)))
1618   {
1619     GNUNET_break (0);
1620     return;
1621   }
1622   if (NULL == session)
1623     session = papi->get_session (papi->cls, address);
1624   if (NULL == session)
1625   {
1626     GNUNET_break (0);
1627     return;
1628   }
1629   connect_msg.header.size = htons (sizeof (struct SessionConnectMessage));
1630   connect_msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_CONNECT_ACK);
1631   connect_msg.reserved = htonl (0);
1632   connect_msg.timestamp = GNUNET_TIME_absolute_hton (timestamp);
1633   (void) papi->send (papi->cls,
1634                      session,
1635                      (const char *) &connect_msg, sizeof (struct SessionConnectMessage),
1636                      UINT_MAX,
1637                      GNUNET_TIME_UNIT_FOREVER_REL,
1638                      NULL, NULL);
1639
1640 }
1641
1642
1643 /**
1644  * Create a fresh entry in the neighbour map for the given peer
1645  *
1646  * @param peer peer to create an entry for
1647  * @return new neighbour map entry
1648  */
1649 static struct NeighbourMapEntry *
1650 setup_neighbour (const struct GNUNET_PeerIdentity *peer)
1651 {
1652   struct NeighbourMapEntry *n;
1653
1654   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1655               "Creating new neighbour entry for `%s'\n",
1656               GNUNET_i2s (peer));
1657   n = GNUNET_malloc (sizeof (struct NeighbourMapEntry));
1658   n->id = *peer;
1659   n->state = S_NOT_CONNECTED;
1660   n->latency = GNUNET_TIME_UNIT_FOREVER_REL;
1661   n->last_util_transmission = GNUNET_TIME_absolute_get();
1662   n->util_payload_bytes_recv = 0;
1663   n->util_payload_bytes_sent = 0;
1664   n->util_total_bytes_recv = 0;
1665   n->util_total_bytes_sent = 0;
1666   GNUNET_BANDWIDTH_tracker_init (&n->in_tracker,
1667                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
1668                                  MAX_BANDWIDTH_CARRY_S);
1669   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
1670   GNUNET_assert (GNUNET_OK ==
1671                  GNUNET_CONTAINER_multipeermap_put (neighbours,
1672                                                     &n->id, n,
1673                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1674   return n;
1675 }
1676
1677
1678 /**
1679  * Check if the two given addresses are the same.
1680  * Actually only checks if the sessions are non-NULL
1681  * (which they should be) and then if they are identical;
1682  * the actual addresses don't matter if the session
1683  * pointers match anyway, and we must have session pointers
1684  * at this time.
1685  *
1686  * @param a1 first address to compare
1687  * @param a2 other address to compare
1688  * @return GNUNET_NO if the addresses do not match, GNUNET_YES if they do match
1689  */
1690 static int
1691 address_matches (const struct NeighbourAddress *a1,
1692                  const struct NeighbourAddress *a2)
1693 {
1694   if ( (NULL == a1->session) ||
1695        (NULL == a2->session) )
1696   {
1697     GNUNET_break (0);
1698     return 0;
1699   }
1700   return (a1->session == a2->session) ? GNUNET_YES : GNUNET_NO;
1701 }
1702
1703
1704 /**
1705  * Try to create a connection to the given target (eventually).
1706  *
1707  * @param target peer to try to connect to
1708  */
1709 void
1710 GST_neighbours_try_connect (const struct GNUNET_PeerIdentity *target)
1711 {
1712   struct NeighbourMapEntry *n;
1713
1714   if (NULL == neighbours)
1715   {
1716           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1717                       "Asked to connect to peer `%s' during shutdown\n",
1718                       GNUNET_i2s (target));
1719                 return; /* during shutdown, do nothing */
1720   }
1721   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1722               "Asked to connect to peer `%s'\n",
1723               GNUNET_i2s (target));
1724   if (0 == memcmp (target, &GST_my_identity, sizeof (struct GNUNET_PeerIdentity)))
1725   {
1726     /* refuse to connect to myself */
1727     /* FIXME: can this happen? Is this not an API violation? */
1728     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1729                 "Refusing to try to connect to myself.\n");
1730     return;
1731   }
1732   n = lookup_neighbour (target);
1733   if (NULL != n)
1734   {
1735     switch (n->state)
1736     {
1737     case S_NOT_CONNECTED:
1738       /* this should not be possible */
1739       GNUNET_break (0);
1740       free_neighbour (n, GNUNET_NO);
1741       break;
1742     case S_INIT_ATS:
1743     case S_INIT_BLACKLIST:
1744     case S_CONNECT_SENT:
1745     case S_CONNECT_RECV_BLACKLIST_INBOUND:
1746     case S_CONNECT_RECV_ATS:
1747     case S_CONNECT_RECV_BLACKLIST:
1748     case S_CONNECT_RECV_ACK:
1749       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1750                 "Ignoring request to try to connect to `%s', already trying!\n",
1751                   GNUNET_i2s (target));
1752       return; /* already trying */
1753     case S_CONNECTED:
1754     case S_RECONNECT_ATS:
1755     case S_RECONNECT_BLACKLIST:
1756     case S_RECONNECT_SENT:
1757     case S_CONNECTED_SWITCHING_BLACKLIST:
1758     case S_CONNECTED_SWITCHING_CONNECT_SENT:
1759       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1760                 "Ignoring request to try to connect, already connected to `%s'!\n",
1761                   GNUNET_i2s (target));
1762       return; /* already connected */
1763     case S_DISCONNECT:
1764       /* get rid of remains, ready to re-try immediately */
1765       free_neighbour (n, GNUNET_NO);
1766       break;
1767     case S_DISCONNECT_FINISHED:
1768       /* should not be possible */
1769       GNUNET_assert (0);
1770     default:
1771       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
1772       GNUNET_break (0);
1773       free_neighbour (n, GNUNET_NO);
1774       break;
1775     }
1776   }
1777   n = setup_neighbour (target);
1778   n->state = S_INIT_ATS;
1779   n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1780
1781   GNUNET_ATS_reset_backoff (GST_ats, target);
1782   n->suggest_handle = GNUNET_ATS_suggest_address (GST_ats, target);
1783 }
1784
1785
1786 /**
1787  * Function called with the result of a blacklist check.
1788  *
1789  * @param cls closure with the 'struct BlackListCheckContext'
1790  * @param peer peer this check affects
1791  * @param result GNUNET_OK if the address is allowed
1792  */
1793 static void
1794 handle_test_blacklist_cont (void *cls,
1795                             const struct GNUNET_PeerIdentity *peer,
1796                             int result)
1797 {
1798   struct BlackListCheckContext *bcc = cls;
1799   struct NeighbourMapEntry *n;
1800
1801   bcc->bc = NULL;
1802   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1803               "Connection to new address of peer `%s' based on blacklist is `%s'\n",
1804               GNUNET_i2s (peer),
1805               (GNUNET_OK == result) ? "allowed" : "FORBIDDEN");
1806   if (NULL == (n = lookup_neighbour (peer)))
1807     goto cleanup; /* nobody left to care about new address */
1808   switch (n->state)
1809   {
1810   case S_NOT_CONNECTED:
1811     /* this should not be possible */
1812     GNUNET_break (0);
1813     free_neighbour (n, GNUNET_NO);
1814     break;
1815   case S_INIT_ATS:
1816     /* still waiting on ATS suggestion */
1817     break;
1818   case S_INIT_BLACKLIST:
1819     /* check if the address the blacklist was fine with matches
1820        ATS suggestion, if so, we can move on! */
1821     if ( (GNUNET_OK == result) &&
1822          (1 == n->send_connect_ack) )
1823     {
1824       n->send_connect_ack = 2;
1825       send_session_connect_ack_message (bcc->na.address,
1826                                         bcc->na.session,
1827                                         n->connect_ack_timestamp);
1828     }
1829     if (GNUNET_YES != address_matches (&bcc->na, &n->primary_address))
1830       break; /* result for an address we currently don't care about */
1831     if (GNUNET_OK == result)
1832     {
1833       n->timeout = GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT);
1834       n->state = S_CONNECT_SENT;
1835       send_session_connect (&n->primary_address);
1836     }
1837     else
1838     {
1839       // FIXME: should also possibly destroy session with plugin!?
1840       GNUNET_ATS_address_destroyed (GST_ats,
1841                                     bcc->na.address,
1842                                     NULL);
1843       free_address (&n->primary_address);
1844       n->state = S_INIT_ATS;
1845       n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1846       // FIXME: do we need to ask ATS again for suggestions?
1847       n->suggest_handle = GNUNET_ATS_suggest_address (GST_ats, &n->id);
1848     }
1849     break;
1850   case S_CONNECT_SENT:
1851     /* waiting on CONNECT_ACK, send ACK if one is pending */
1852     if ( (GNUNET_OK == result) &&
1853          (1 == n->send_connect_ack) )
1854     {
1855       n->send_connect_ack = 2;
1856       send_session_connect_ack_message (n->primary_address.address,
1857                                         n->primary_address.session,
1858                                         n->connect_ack_timestamp);
1859     }
1860     break;
1861   case S_CONNECT_RECV_BLACKLIST_INBOUND:
1862     if (GNUNET_OK == result)
1863         GST_ats_add_address (bcc->na.address, bcc->na.session);
1864
1865     n->state = S_CONNECT_RECV_ATS;
1866     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1867     GNUNET_ATS_reset_backoff (GST_ats, peer);
1868     n->suggest_handle = GNUNET_ATS_suggest_address (GST_ats, peer);
1869     break;
1870   case S_CONNECT_RECV_ATS:
1871     /* still waiting on ATS suggestion, don't care about blacklist */
1872     break;
1873   case S_CONNECT_RECV_BLACKLIST:
1874     if (GNUNET_YES != address_matches (&bcc->na, &n->primary_address))
1875       break; /* result for an address we currently don't care about */
1876     if (GNUNET_OK == result)
1877     {
1878       n->timeout = GNUNET_TIME_relative_to_absolute (SETUP_CONNECTION_TIMEOUT);
1879       n->state = S_CONNECT_RECV_ACK;
1880       send_session_connect_ack_message (bcc->na.address,
1881                                         bcc->na.session,
1882                                         n->connect_ack_timestamp);
1883       if (1 == n->send_connect_ack)
1884         n->send_connect_ack = 2;
1885     }
1886     else
1887     {
1888       // FIXME: should also possibly destroy session with plugin!?
1889       GNUNET_ATS_address_destroyed (GST_ats,
1890                                     bcc->na.address,
1891                                     NULL);
1892       free_address (&n->primary_address);
1893       n->state = S_INIT_ATS;
1894       n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1895       // FIXME: do we need to ask ATS again for suggestions?
1896       GNUNET_ATS_reset_backoff (GST_ats, peer);
1897       n->suggest_handle = GNUNET_ATS_suggest_address (GST_ats, &n->id);
1898     }
1899     break;
1900   case S_CONNECT_RECV_ACK:
1901     /* waiting on SESSION_ACK, send ACK if one is pending */
1902     if ( (GNUNET_OK == result) &&
1903          (1 == n->send_connect_ack) )
1904     {
1905       n->send_connect_ack = 2;
1906       send_session_connect_ack_message (n->primary_address.address,
1907                                         n->primary_address.session,
1908                                         n->connect_ack_timestamp);
1909     }
1910     break;
1911   case S_CONNECTED:
1912     /* already connected, don't care about blacklist */
1913     break;
1914   case S_RECONNECT_ATS:
1915     /* still waiting on ATS suggestion, don't care about blacklist */
1916     break;
1917   case S_RECONNECT_BLACKLIST:
1918     if ( (GNUNET_OK == result) &&
1919          (1 == n->send_connect_ack) )
1920     {
1921       n->send_connect_ack = 2;
1922       send_session_connect_ack_message (bcc->na.address,
1923                                         bcc->na.session,
1924                                         n->connect_ack_timestamp);
1925     }
1926     if (GNUNET_YES != address_matches (&bcc->na, &n->primary_address))
1927       break; /* result for an address we currently don't care about */
1928     if (GNUNET_OK == result)
1929     {
1930       send_session_connect (&n->primary_address);
1931       n->timeout = GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT);
1932       n->state = S_RECONNECT_SENT;
1933     }
1934     else
1935     {
1936       GNUNET_ATS_address_destroyed (GST_ats,
1937                                     bcc->na.address,
1938                                     NULL);
1939       n->state = S_RECONNECT_ATS;
1940       n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
1941       // FIXME: do we need to ask ATS again for suggestions?
1942       n->suggest_handle = GNUNET_ATS_suggest_address (GST_ats, &n->id);
1943     }
1944     break;
1945   case S_RECONNECT_SENT:
1946     /* waiting on CONNECT_ACK, don't care about blacklist */
1947     if ( (GNUNET_OK == result) &&
1948          (1 == n->send_connect_ack) )
1949     {
1950       n->send_connect_ack = 2;
1951       send_session_connect_ack_message (n->primary_address.address,
1952                                         n->primary_address.session,
1953                                         n->connect_ack_timestamp);
1954     }
1955     break;
1956   case S_CONNECTED_SWITCHING_BLACKLIST:
1957     if (GNUNET_YES != address_matches (&bcc->na, &n->alternative_address))
1958       break; /* result for an address we currently don't care about */
1959     if (GNUNET_OK == result)
1960     {
1961       send_session_connect (&n->alternative_address);
1962       n->state = S_CONNECTED_SWITCHING_CONNECT_SENT;
1963     }
1964     else
1965     {
1966       GNUNET_ATS_address_destroyed (GST_ats,
1967                                     bcc->na.address,
1968                                     NULL);
1969       free_address (&n->alternative_address);
1970       n->state = S_CONNECTED;
1971     }
1972     break;
1973   case S_CONNECTED_SWITCHING_CONNECT_SENT:
1974     /* waiting on CONNECT_ACK, don't care about blacklist */
1975     if ( (GNUNET_OK == result) &&
1976          (1 == n->send_connect_ack) )
1977     {
1978       n->send_connect_ack = 2;
1979       send_session_connect_ack_message (n->primary_address.address,
1980                                         n->primary_address.session,
1981                                         n->connect_ack_timestamp);
1982     }
1983     break;
1984   case S_DISCONNECT:
1985     /* Nothing to do here, ATS will already do what can be done */
1986     break;
1987   case S_DISCONNECT_FINISHED:
1988     /* should not be possible */
1989     GNUNET_assert (0);
1990     break;
1991   default:
1992     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
1993     GNUNET_break (0);
1994     free_neighbour (n, GNUNET_NO);
1995     break;
1996   }
1997  cleanup:
1998   GNUNET_HELLO_address_free (bcc->na.address);
1999   GNUNET_CONTAINER_DLL_remove (bc_head,
2000                                bc_tail,
2001                                bcc);
2002   GNUNET_free (bcc);
2003 }
2004
2005
2006 /**
2007  * We want to know if connecting to a particular peer via
2008  * a particular address is allowed.  Check it!
2009  *
2010  * @param peer identity of the peer to switch the address for
2011  * @param ts time at which the check was initiated
2012  * @param address address of the other peer, NULL if other peer
2013  *                       connected to us
2014  * @param session session to use (or NULL)
2015  */
2016 static void
2017 check_blacklist (const struct GNUNET_PeerIdentity *peer,
2018                  struct GNUNET_TIME_Absolute ts,
2019                  const struct GNUNET_HELLO_Address *address,
2020                  struct Session *session)
2021 {
2022   struct BlackListCheckContext *bcc;
2023   struct GST_BlacklistCheck *bc;
2024
2025   bcc = GNUNET_malloc (sizeof (struct BlackListCheckContext));
2026   bcc->na.address = GNUNET_HELLO_address_copy (address);
2027   bcc->na.session = session;
2028   bcc->na.connect_timestamp = ts;
2029   GNUNET_CONTAINER_DLL_insert (bc_head,
2030                                bc_tail,
2031                                bcc);
2032   if (NULL != (bc = GST_blacklist_test_allowed (peer,
2033                                                 address->transport_name,
2034                                                 &handle_test_blacklist_cont, bcc)))
2035     bcc->bc = bc;
2036   /* if NULL == bc, 'cont' was already called and 'bcc' already free'd, so
2037      we must only store 'bc' if 'bc' is non-NULL... */
2038 }
2039
2040
2041 /**
2042  * We received a 'SESSION_CONNECT' message from the other peer.
2043  * Consider switching to it.
2044  *
2045  * @param message possibly a 'struct SessionConnectMessage' (check format)
2046  * @param peer identity of the peer to switch the address for
2047  * @param address address of the other peer, NULL if other peer
2048  *                       connected to us
2049  * @param session session to use (or NULL)
2050  */
2051 void
2052 GST_neighbours_handle_connect (const struct GNUNET_MessageHeader *message,
2053                                const struct GNUNET_PeerIdentity *peer,
2054                                const struct GNUNET_HELLO_Address *address,
2055                                struct Session *session)
2056 {
2057   const struct SessionConnectMessage *scm;
2058   struct NeighbourMapEntry *n;
2059   struct GNUNET_TIME_Absolute ts;
2060
2061   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2062               "Received CONNECT message from peer `%s'\n",
2063               GNUNET_i2s (peer));
2064
2065   if (ntohs (message->size) != sizeof (struct SessionConnectMessage))
2066   {
2067     GNUNET_break_op (0);
2068     return;
2069   }
2070   if (NULL == neighbours)
2071     return; /* we're shutting down */
2072   scm = (const struct SessionConnectMessage *) message;
2073   GNUNET_break_op (0 == ntohl (scm->reserved));
2074   ts = GNUNET_TIME_absolute_ntoh (scm->timestamp);
2075   n = lookup_neighbour (peer);
2076   if (NULL == n)
2077     n = setup_neighbour (peer);
2078   n->send_connect_ack = 1;
2079   n->connect_ack_timestamp = ts;
2080
2081   switch (n->state)
2082   {
2083   case S_NOT_CONNECTED:
2084     n->state = S_CONNECT_RECV_BLACKLIST_INBOUND;
2085     /* Do a blacklist check for the new address */
2086     check_blacklist (peer, ts, address, session);
2087     break;
2088   case S_INIT_ATS:
2089     /* CONNECT message takes priority over us asking ATS for address */
2090     n->state = S_CONNECT_RECV_BLACKLIST_INBOUND;
2091     /* fallthrough */
2092   case S_INIT_BLACKLIST:
2093   case S_CONNECT_SENT:
2094   case S_CONNECT_RECV_BLACKLIST_INBOUND:
2095   case S_CONNECT_RECV_ATS:
2096   case S_CONNECT_RECV_BLACKLIST:
2097   case S_CONNECT_RECV_ACK:
2098     /* It can never hurt to have an alternative address in the above cases,
2099        see if it is allowed */
2100     check_blacklist (peer, ts, address, session);
2101     break;
2102   case S_CONNECTED:
2103     /* we are already connected and can thus send the ACK immediately;
2104        still, it can never hurt to have an alternative address, so also
2105        tell ATS  about it */
2106     GNUNET_assert (NULL != n->primary_address.address);
2107     GNUNET_assert (NULL != n->primary_address.session);
2108     n->send_connect_ack = 0;
2109     send_session_connect_ack_message (n->primary_address.address,
2110                                       n->primary_address.session, ts);
2111     check_blacklist (peer, ts, address, session);
2112     break;
2113   case S_RECONNECT_ATS:
2114   case S_RECONNECT_BLACKLIST:
2115   case S_RECONNECT_SENT:
2116     /* It can never hurt to have an alternative address in the above cases,
2117        see if it is allowed */
2118     check_blacklist (peer, ts, address, session);
2119     break;
2120   case S_CONNECTED_SWITCHING_BLACKLIST:
2121   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2122     /* we are already connected and can thus send the ACK immediately;
2123        still, it can never hurt to have an alternative address, so also
2124        tell ATS  about it */
2125     GNUNET_assert (NULL != n->primary_address.address);
2126     GNUNET_assert (NULL != n->primary_address.session);
2127     n->send_connect_ack = 0;
2128     send_session_connect_ack_message (n->primary_address.address,
2129                                       n->primary_address.session, ts);
2130     check_blacklist (peer, ts, address, session);
2131     break;
2132   case S_DISCONNECT:
2133     /* get rid of remains without terminating sessions, ready to re-try */
2134     free_neighbour (n, GNUNET_YES);
2135     n = setup_neighbour (peer);
2136     n->state = S_CONNECT_RECV_ATS;
2137     GNUNET_ATS_reset_backoff (GST_ats, peer);
2138     n->suggest_handle = GNUNET_ATS_suggest_address (GST_ats, peer);
2139     break;
2140   case S_DISCONNECT_FINISHED:
2141     /* should not be possible */
2142     GNUNET_assert (0);
2143     break;
2144   default:
2145     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2146     GNUNET_break (0);
2147     free_neighbour (n, GNUNET_NO);
2148     break;
2149   }
2150 }
2151
2152
2153 /**
2154  * For an existing neighbour record, set the active connection to
2155  * use the given address.
2156  *
2157  * @param peer identity of the peer to switch the address for
2158  * @param address address of the other peer, NULL if other peer
2159  *                       connected to us
2160  * @param session session to use (or NULL)
2161  * @param ats performance data
2162  * @param ats_count number of entries in ats
2163  * @param bandwidth_in inbound quota to be used when connection is up,
2164  *      0 to disconnect from peer
2165  * @param bandwidth_out outbound quota to be used when connection is up,
2166  *      0 to disconnect from peer
2167  */
2168 void
2169 GST_neighbours_switch_to_address (const struct GNUNET_PeerIdentity *peer,
2170                                   const struct GNUNET_HELLO_Address *address,
2171                                   struct Session *session,
2172                                   const struct GNUNET_ATS_Information *ats,
2173                                   uint32_t ats_count,
2174                                   struct GNUNET_BANDWIDTH_Value32NBO
2175                                   bandwidth_in,
2176                                   struct GNUNET_BANDWIDTH_Value32NBO
2177                                   bandwidth_out)
2178 {
2179   struct NeighbourMapEntry *n;
2180   struct GNUNET_TRANSPORT_PluginFunctions *papi;
2181
2182   GNUNET_assert (address->transport_name != NULL);
2183   if (NULL == (n = lookup_neighbour (peer)))
2184     return;
2185
2186   /* Obtain an session for this address from plugin */
2187   if (NULL == (papi = GST_plugins_find (address->transport_name)))
2188   {
2189     /* we don't have the plugin for this address */
2190     GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
2191     return;
2192   }
2193   if ((NULL == session) && (0 == address->address_length))
2194   {
2195     GNUNET_break (0);
2196     if (strlen (address->transport_name) > 0)
2197       GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
2198     return;
2199   }
2200
2201   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2202               "ATS tells us to switch to address '%s' session %p for "
2203               "peer `%s' in state %s (quota in/out %u %u )\n",
2204               (address->address_length != 0) ? GST_plugins_a2s (address): "<inbound>",
2205               session,
2206               GNUNET_i2s (peer),
2207               print_state (n->state),
2208               ntohl (bandwidth_in.value__),
2209               ntohl (bandwidth_out.value__));
2210
2211   if (NULL == session)
2212   {
2213     session = papi->get_session (papi->cls, address);
2214     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2215                 "Obtained new session for peer `%s' and  address '%s': %p\n",
2216                 GNUNET_i2s (&address->peer), GST_plugins_a2s (address), session);
2217   }
2218   if (NULL == session)
2219   {
2220     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2221                 "Failed to obtain new session for peer `%s' and  address '%s'\n",
2222                 GNUNET_i2s (&address->peer), GST_plugins_a2s (address));
2223     GNUNET_ATS_address_destroyed (GST_ats, address, NULL);
2224     return;
2225   }
2226   switch (n->state)
2227   {
2228   case S_NOT_CONNECTED:
2229     GNUNET_break (0);
2230     free_neighbour (n, GNUNET_NO);
2231     return;
2232   case S_INIT_ATS:
2233     set_address (&n->primary_address,
2234                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2235     n->state = S_INIT_BLACKLIST;
2236     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2237     check_blacklist (&n->id,
2238                      n->connect_ack_timestamp,
2239                      address, session);
2240     break;
2241   case S_INIT_BLACKLIST:
2242     /* ATS suggests a different address, switch again */
2243     set_address (&n->primary_address,
2244                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2245     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2246     check_blacklist (&n->id,
2247                      n->connect_ack_timestamp,
2248                      address, session);
2249     break;
2250   case S_CONNECT_SENT:
2251     /* ATS suggests a different address, switch again */
2252     set_address (&n->primary_address,
2253                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2254     n->state = S_INIT_BLACKLIST;
2255     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2256     check_blacklist (&n->id,
2257                      n->connect_ack_timestamp,
2258                      address, session);
2259     break;
2260   case S_CONNECT_RECV_ATS:
2261     set_address (&n->primary_address,
2262                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2263     n->state = S_CONNECT_RECV_BLACKLIST;
2264     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2265     check_blacklist (&n->id,
2266                      n->connect_ack_timestamp,
2267                      address, session);
2268     break;
2269   case S_CONNECT_RECV_BLACKLIST_INBOUND:
2270     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2271     check_blacklist (&n->id,
2272                      n->connect_ack_timestamp,
2273                      address, session);
2274     break;
2275   case S_CONNECT_RECV_BLACKLIST:
2276   case S_CONNECT_RECV_ACK:
2277     /* ATS asks us to switch while we were trying to connect; switch to new
2278        address and check blacklist again */
2279     set_address (&n->primary_address,
2280                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2281     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2282     check_blacklist (&n->id,
2283                      n->connect_ack_timestamp,
2284                      address, session);
2285     break;
2286   case S_CONNECTED:
2287     GNUNET_assert (NULL != n->primary_address.address);
2288     GNUNET_assert (NULL != n->primary_address.session);
2289     if (n->primary_address.session == session)
2290     {
2291       /* not an address change, just a quota change */
2292       set_address (&n->primary_address,
2293                    address, session, bandwidth_in, bandwidth_out, GNUNET_YES);
2294       break;
2295     }
2296     /* ATS asks us to switch a life connection; see if we can get
2297        a CONNECT_ACK on it before we actually do this! */
2298     set_address (&n->alternative_address,
2299                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2300     n->state = S_CONNECTED_SWITCHING_BLACKLIST;
2301     check_blacklist (&n->id,
2302                      GNUNET_TIME_absolute_get (),
2303                      address, session);
2304     break;
2305   case S_RECONNECT_ATS:
2306     set_address (&n->primary_address,
2307                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2308     n->state = S_RECONNECT_BLACKLIST;
2309     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2310     check_blacklist (&n->id,
2311                      n->connect_ack_timestamp,
2312                      address, session);
2313     break;
2314   case S_RECONNECT_BLACKLIST:
2315     /* ATS asks us to switch while we were trying to reconnect; switch to new
2316        address and check blacklist again */
2317     set_address (&n->primary_address,
2318                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2319     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2320     check_blacklist (&n->id,
2321                      n->connect_ack_timestamp,
2322                      address, session);
2323     break;
2324   case S_RECONNECT_SENT:
2325     /* ATS asks us to switch while we were trying to reconnect; switch to new
2326        address and check blacklist again */
2327     set_address (&n->primary_address,
2328                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2329     n->state = S_RECONNECT_BLACKLIST;
2330     n->timeout = GNUNET_TIME_relative_to_absolute (BLACKLIST_RESPONSE_TIMEOUT);
2331     check_blacklist (&n->id,
2332                      n->connect_ack_timestamp,
2333                      address, session);
2334     break;
2335   case S_CONNECTED_SWITCHING_BLACKLIST:
2336     if (n->primary_address.session == session)
2337     {
2338       /* ATS switches back to still-active session */
2339       free_address (&n->alternative_address);
2340       n->state = S_CONNECTED;
2341       break;
2342     }
2343     /* ATS asks us to switch a life connection, update blacklist check */
2344     set_address (&n->alternative_address,
2345                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2346     check_blacklist (&n->id,
2347                      GNUNET_TIME_absolute_get (),
2348                      address, session);
2349     break;
2350   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2351     if (n->primary_address.session == session)
2352     {
2353       /* ATS switches back to still-active session */
2354       free_address (&n->alternative_address);
2355       n->state = S_CONNECTED;
2356       break;
2357     }
2358     /* ATS asks us to switch a life connection, update blacklist check */
2359     set_address (&n->alternative_address,
2360                  address, session, bandwidth_in, bandwidth_out, GNUNET_NO);
2361     n->state = S_CONNECTED_SWITCHING_BLACKLIST;
2362     check_blacklist (&n->id,
2363                      GNUNET_TIME_absolute_get (),
2364                      address, session);
2365     break;
2366   case S_DISCONNECT:
2367     /* not going to switch addresses while disconnecting */
2368     return;
2369   case S_DISCONNECT_FINISHED:
2370     GNUNET_assert (0);
2371     break;
2372   default:
2373     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2374     GNUNET_break (0);
2375     break;
2376   }
2377 }
2378
2379 static int
2380 send_utilization_data (void *cls,
2381     const struct GNUNET_PeerIdentity *key,
2382     void *value)
2383 {
2384   struct NeighbourMapEntry *n = value;
2385   struct GNUNET_ATS_Information atsi[4];
2386   uint32_t bps_pl_in;
2387   uint32_t bps_pl_out;
2388   uint32_t bps_in;
2389   uint32_t bps_out;
2390   struct GNUNET_TIME_Relative delta;
2391
2392   delta = GNUNET_TIME_absolute_get_difference(n->last_util_transmission, GNUNET_TIME_absolute_get());
2393
2394   bps_pl_in = 0;
2395
2396   if ((0 != n->util_payload_bytes_recv) && (0 != delta.rel_value_us))
2397     bps_pl_in =  (1000LL * 1000LL *  n->util_payload_bytes_recv) / (delta.rel_value_us);
2398   bps_pl_out = 0;
2399   if ((0 != n->util_payload_bytes_sent) && (0 != delta.rel_value_us))
2400     bps_pl_out = (1000LL * 1000LL * n->util_payload_bytes_sent) / delta.rel_value_us;
2401   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s' payload: received %u Bytes/s, sent %u Bytes/s  \n",
2402       GNUNET_i2s (key), bps_pl_in, bps_pl_out);
2403
2404   bps_in = 0;
2405   if ((0 != n->util_total_bytes_recv) && (0 != delta.rel_value_us))
2406     bps_in =  (1000LL * 1000LL *  n->util_total_bytes_recv) / (delta.rel_value_us);
2407   bps_out = 0;
2408   if ((0 != n->util_total_bytes_sent) && (0 != delta.rel_value_us))
2409     bps_out = (1000LL * 1000LL * n->util_total_bytes_sent) / delta.rel_value_us;
2410
2411
2412   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s' total: received %u Bytes/s, sent %u Bytes/s  \n",
2413       GNUNET_i2s (key), bps_in, bps_out);
2414
2415   atsi[0].type = htonl (GNUNET_ATS_UTILIZATION_OUT);
2416   atsi[0].value = htonl (bps_out);
2417   atsi[1].type = htonl (GNUNET_ATS_UTILIZATION_IN);
2418   atsi[1].value = htonl (bps_in);
2419
2420   atsi[2].type = htonl (GNUNET_ATS_UTILIZATION_PAYLOAD_OUT);
2421   atsi[2].value = htonl (bps_pl_out);
2422   atsi[3].type = htonl (GNUNET_ATS_UTILIZATION_PAYLOAD_IN);
2423   atsi[3].value = htonl (bps_pl_in);
2424
2425   GST_ats_update_metrics (key, n->primary_address.address,
2426       n->primary_address.session, atsi, 4);
2427   n->util_payload_bytes_recv = 0;
2428   n->util_payload_bytes_sent = 0;
2429   n->util_total_bytes_recv = 0;
2430   n->util_total_bytes_sent = 0;
2431   n->last_util_transmission = GNUNET_TIME_absolute_get();
2432   return GNUNET_OK;
2433 }
2434
2435 /**
2436  * Task transmitting utilization in a regular interval
2437  *
2438  * @param cls the 'struct NeighbourMapEntry' for which we are running
2439  * @param tc scheduler context (unused)
2440  */
2441 static void
2442 utilization_transmission (void *cls,
2443              const struct GNUNET_SCHEDULER_TaskContext *tc)
2444 {
2445   util_transmission_tk = GNUNET_SCHEDULER_NO_TASK;
2446
2447   if (0 < GNUNET_CONTAINER_multipeermap_size (neighbours))
2448     GNUNET_CONTAINER_multipeermap_iterate (neighbours, send_utilization_data, NULL);
2449
2450   util_transmission_tk = GNUNET_SCHEDULER_add_delayed (UTIL_TRANSMISSION_INTERVAL,
2451       utilization_transmission, NULL);
2452
2453 }
2454
2455 void
2456 GST_neighbours_notify_data_recv (const struct GNUNET_PeerIdentity *peer,
2457                  const struct GNUNET_HELLO_Address *address,
2458                  struct Session *session,
2459                  const struct GNUNET_MessageHeader *message)
2460 {
2461   struct NeighbourMapEntry *n;
2462   n = lookup_neighbour (peer);
2463   if (NULL == n)
2464   {
2465       return;
2466   }
2467   n->util_total_bytes_recv += ntohs(message->size);
2468 }
2469
2470 void
2471 GST_neighbours_notify_payload_recv (const struct GNUNET_PeerIdentity *peer,
2472                  const struct GNUNET_HELLO_Address *address,
2473                  struct Session *session,
2474                  const struct GNUNET_MessageHeader *message)
2475 {
2476   struct NeighbourMapEntry *n;
2477   n = lookup_neighbour (peer);
2478   if (NULL == n)
2479   {
2480       return;
2481   }
2482   n->util_payload_bytes_recv += ntohs(message->size);
2483 }
2484
2485
2486 void
2487 GST_neighbours_notify_data_sent (const struct GNUNET_PeerIdentity *peer,
2488                      const struct GNUNET_HELLO_Address *address,
2489                      struct Session *session,
2490                      size_t size)
2491 {
2492   struct NeighbourMapEntry *n;
2493   n = lookup_neighbour (peer);
2494   if (NULL == n)
2495       return;
2496   if (n->primary_address.session != session)
2497     return;
2498   n->util_total_bytes_sent += size;
2499 }
2500
2501 void
2502 GST_neighbours_notify_payload_sent (const struct GNUNET_PeerIdentity *peer,
2503     size_t size)
2504 {
2505   struct NeighbourMapEntry *n;
2506   n = lookup_neighbour (peer);
2507   if (NULL == n)
2508   {
2509       return;
2510   }
2511   n->util_payload_bytes_sent += size;
2512 }
2513
2514
2515 /**
2516  * Master task run for every neighbour.  Performs all of the time-related
2517  * activities (keep alive, send next message, disconnect if idle, finish
2518  * clean up after disconnect).
2519  *
2520  * @param cls the 'struct NeighbourMapEntry' for which we are running
2521  * @param tc scheduler context (unused)
2522  */
2523 static void
2524 master_task (void *cls,
2525              const struct GNUNET_SCHEDULER_TaskContext *tc)
2526 {
2527   struct NeighbourMapEntry *n = cls;
2528   struct GNUNET_TIME_Relative delay;
2529
2530   n->task = GNUNET_SCHEDULER_NO_TASK;
2531   delay = GNUNET_TIME_absolute_get_remaining (n->timeout);
2532   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2533               "Master task runs for neighbour `%s' in state %s with timeout in %s\n",
2534               GNUNET_i2s (&n->id),
2535               print_state(n->state),
2536               GNUNET_STRINGS_relative_time_to_string (delay,
2537                                                       GNUNET_YES));
2538   switch (n->state)
2539   {
2540   case S_NOT_CONNECTED:
2541     /* invalid state for master task, clean up */
2542     GNUNET_break (0);
2543     n->state = S_DISCONNECT_FINISHED;
2544     free_neighbour (n, GNUNET_NO);
2545     return;
2546   case S_INIT_ATS:
2547     if (0 == delay.rel_value_us)
2548     {
2549       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2550                   "Connection to `%s' timed out waiting for ATS to provide address\n",
2551                   GNUNET_i2s (&n->id));
2552       n->state = S_DISCONNECT_FINISHED;
2553       free_neighbour (n, GNUNET_NO);
2554       return;
2555     }
2556     break;
2557   case S_INIT_BLACKLIST:
2558     if (0 == delay.rel_value_us)
2559     {
2560       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2561                   "Connection to `%s' timed out waiting for BLACKLIST to approve address\n",
2562                   GNUNET_i2s (&n->id));
2563       n->state = S_DISCONNECT_FINISHED;
2564       free_neighbour (n, GNUNET_NO);
2565       return;
2566     }
2567     break;
2568   case S_CONNECT_SENT:
2569     if (0 == delay.rel_value_us)
2570     {
2571       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2572                   "Connection to `%s' timed out waiting for other peer to send CONNECT_ACK\n",
2573                   GNUNET_i2s (&n->id));
2574       disconnect_neighbour (n);
2575       return;
2576     }
2577     break;
2578   case S_CONNECT_RECV_BLACKLIST_INBOUND:
2579     if (0 == delay.rel_value_us)
2580     {
2581       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2582                   "Connection to `%s' timed out waiting BLACKLIST to approve address to use for received CONNECT\n",
2583                   GNUNET_i2s (&n->id));
2584       n->state = S_DISCONNECT_FINISHED;
2585       free_neighbour (n, GNUNET_NO);
2586       return;
2587     }
2588     break;
2589   case S_CONNECT_RECV_ATS:
2590     if (0 == delay.rel_value_us)
2591     {
2592       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2593                   "Connection to `%s' timed out waiting ATS to provide address to use for CONNECT_ACK\n",
2594                   GNUNET_i2s (&n->id));
2595       n->state = S_DISCONNECT_FINISHED;
2596       free_neighbour (n, GNUNET_NO);
2597       return;
2598     }
2599     break;
2600   case S_CONNECT_RECV_BLACKLIST:
2601     if (0 == delay.rel_value_us)
2602     {
2603       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2604                   "Connection to `%s' timed out waiting BLACKLIST to approve address to use for CONNECT_ACK\n",
2605                   GNUNET_i2s (&n->id));
2606       n->state = S_DISCONNECT_FINISHED;
2607       free_neighbour (n, GNUNET_NO);
2608       return;
2609     }
2610     break;
2611   case S_CONNECT_RECV_ACK:
2612     if (0 == delay.rel_value_us)
2613     {
2614       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2615                   "Connection to `%s' timed out waiting for other peer to send SESSION_ACK\n",
2616                   GNUNET_i2s (&n->id));
2617       disconnect_neighbour (n);
2618       return;
2619     }
2620     break;
2621   case S_CONNECTED:
2622     if (0 == delay.rel_value_us)
2623     {
2624       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2625                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs\n",
2626                   GNUNET_i2s (&n->id));
2627       disconnect_neighbour (n);
2628       return;
2629     }
2630     try_transmission_to_peer (n);
2631     send_keepalive (n);
2632     break;
2633   case S_RECONNECT_ATS:
2634     if (0 == delay.rel_value_us)
2635     {
2636       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2637                   "Connection to `%s' timed out, waiting for ATS replacement address\n",
2638                   GNUNET_i2s (&n->id));
2639       disconnect_neighbour (n);
2640       return;
2641     }
2642     break;
2643   case S_RECONNECT_BLACKLIST:
2644     if (0 == delay.rel_value_us)
2645     {
2646       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2647                   "Connection to `%s' timed out, waiting for BLACKLIST to approve replacement address\n",
2648                   GNUNET_i2s (&n->id));
2649       disconnect_neighbour (n);
2650       return;
2651     }
2652     break;
2653   case S_RECONNECT_SENT:
2654     if (0 == delay.rel_value_us)
2655     {
2656       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2657                   "Connection to `%s' timed out, waiting for other peer to CONNECT_ACK replacement address\n",
2658                   GNUNET_i2s (&n->id));
2659       disconnect_neighbour (n);
2660       return;
2661     }
2662     break;
2663   case S_CONNECTED_SWITCHING_BLACKLIST:
2664     if (0 == delay.rel_value_us)
2665     {
2666       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2667                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs\n",
2668                   GNUNET_i2s (&n->id));
2669       disconnect_neighbour (n);
2670       return;
2671     }
2672     try_transmission_to_peer (n);
2673     send_keepalive (n);
2674     break;
2675   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2676     if (0 == delay.rel_value_us)
2677     {
2678       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2679                   "Connection to `%s' timed out, missing KEEPALIVE_RESPONSEs (after trying to CONNECT on alternative address)\n",
2680                   GNUNET_i2s (&n->id));
2681       disconnect_neighbour (n);
2682       return;
2683     }
2684     try_transmission_to_peer (n);
2685     send_keepalive (n);
2686     break;
2687   case S_DISCONNECT:
2688     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2689                 "Cleaning up connection to `%s' after sending DISCONNECT\n",
2690                 GNUNET_i2s (&n->id));
2691     free_neighbour (n, GNUNET_NO);
2692     return;
2693   case S_DISCONNECT_FINISHED:
2694     /* how did we get here!? */
2695     GNUNET_assert (0);
2696     break;
2697   default:
2698     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2699     GNUNET_break (0);
2700     break;
2701   }
2702   if ( (S_CONNECTED_SWITCHING_CONNECT_SENT == n->state) ||
2703        (S_CONNECTED_SWITCHING_BLACKLIST == n->state) ||
2704        (S_CONNECTED == n->state) )
2705   {
2706     /* if we are *now* in one of these three states, we're sending
2707        keep alive messages, so we need to consider the keepalive
2708        delay, not just the connection timeout */
2709     delay = GNUNET_TIME_relative_min (GNUNET_TIME_absolute_get_remaining (n->keep_alive_time),
2710                                       delay);
2711   }
2712   if (GNUNET_SCHEDULER_NO_TASK == n->task)
2713     n->task = GNUNET_SCHEDULER_add_delayed (delay,
2714                                             &master_task,
2715                                             n);
2716 }
2717
2718
2719 /**
2720  * Send a SESSION_ACK message to the neighbour to confirm that we
2721  * got his CONNECT_ACK.
2722  *
2723  * @param n neighbour to send the SESSION_ACK to
2724  */
2725 static void
2726 send_session_ack_message (struct NeighbourMapEntry *n)
2727 {
2728   struct GNUNET_MessageHeader msg;
2729
2730   msg.size = htons (sizeof (struct GNUNET_MessageHeader));
2731   msg.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_ACK);
2732   (void) send_with_session(n,
2733                            (const char *) &msg, sizeof (struct GNUNET_MessageHeader),
2734                            UINT32_MAX, GNUNET_TIME_UNIT_FOREVER_REL,
2735                            NULL, NULL);
2736 }
2737
2738
2739 /**
2740  * We received a 'SESSION_CONNECT_ACK' message from the other peer.
2741  * Consider switching to it.
2742  *
2743  * @param message possibly a 'struct SessionConnectMessage' (check format)
2744  * @param peer identity of the peer to switch the address for
2745  * @param address address of the other peer, NULL if other peer
2746  *                       connected to us
2747  * @param session session to use (or NULL)
2748  */
2749 void
2750 GST_neighbours_handle_connect_ack (const struct GNUNET_MessageHeader *message,
2751                                    const struct GNUNET_PeerIdentity *peer,
2752                                    const struct GNUNET_HELLO_Address *address,
2753                                    struct Session *session)
2754 {
2755   const struct SessionConnectMessage *scm;
2756   struct GNUNET_TIME_Absolute ts;
2757   struct NeighbourMapEntry *n;
2758
2759   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2760               "Received CONNECT_ACK message from peer `%s'\n",
2761               GNUNET_i2s (peer));
2762
2763   if (ntohs (message->size) != sizeof (struct SessionConnectMessage))
2764   {
2765     GNUNET_break_op (0);
2766     return;
2767   }
2768   scm = (const struct SessionConnectMessage *) message;
2769   GNUNET_break_op (ntohl (scm->reserved) == 0);
2770   if (NULL == (n = lookup_neighbour (peer)))
2771   {
2772     GNUNET_STATISTICS_update (GST_stats,
2773                               gettext_noop
2774                               ("# unexpected CONNECT_ACK messages (no peer)"),
2775                               1, GNUNET_NO);
2776     return;
2777   }
2778   ts = GNUNET_TIME_absolute_ntoh (scm->timestamp);
2779   switch (n->state)
2780   {
2781   case S_NOT_CONNECTED:
2782     GNUNET_break (0);
2783     free_neighbour (n, GNUNET_NO);
2784     return;
2785   case S_INIT_ATS:
2786   case S_INIT_BLACKLIST:
2787     GNUNET_STATISTICS_update (GST_stats,
2788                               gettext_noop
2789                               ("# unexpected CONNECT_ACK messages (not ready)"),
2790                               1, GNUNET_NO);
2791     break;
2792   case S_CONNECT_SENT:
2793     if (ts.abs_value_us != n->primary_address.connect_timestamp.abs_value_us)
2794       break; /* ACK does not match our original CONNECT message */
2795     n->state = S_CONNECTED;
2796     n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2797     GNUNET_STATISTICS_set (GST_stats,
2798                            gettext_noop ("# peers connected"),
2799                            ++neighbours_connected,
2800                            GNUNET_NO);
2801     connect_notify_cb (callback_cls, &n->id,
2802                        n->primary_address.bandwidth_in,
2803                        n->primary_address.bandwidth_out);
2804     /* Tell ATS that the outbound session we created to send CONNECT was successfull */
2805     GST_ats_add_address (n->primary_address.address, n->primary_address.session);
2806     set_address (&n->primary_address,
2807                  n->primary_address.address,
2808                  n->primary_address.session,
2809                  n->primary_address.bandwidth_in,
2810                  n->primary_address.bandwidth_out,
2811                  GNUNET_YES);
2812     send_session_ack_message (n);
2813     break;
2814   case S_CONNECT_RECV_BLACKLIST_INBOUND:
2815   case S_CONNECT_RECV_ATS:
2816   case S_CONNECT_RECV_BLACKLIST:
2817   case S_CONNECT_RECV_ACK:
2818     GNUNET_STATISTICS_update (GST_stats,
2819                               gettext_noop
2820                               ("# unexpected CONNECT_ACK messages (not ready)"),
2821                               1, GNUNET_NO);
2822     break;
2823   case S_CONNECTED:
2824     /* duplicate CONNECT_ACK, let's answer by duplciate SESSION_ACK just in case */
2825     send_session_ack_message (n);
2826     break;
2827   case S_RECONNECT_ATS:
2828   case S_RECONNECT_BLACKLIST:
2829     /* we didn't expect any CONNECT_ACK, as we are waiting for ATS
2830        to give us a new address... */
2831     GNUNET_STATISTICS_update (GST_stats,
2832                               gettext_noop
2833                               ("# unexpected CONNECT_ACK messages (waiting on ATS)"),
2834                               1, GNUNET_NO);
2835     break;
2836   case S_RECONNECT_SENT:
2837     /* new address worked; go back to connected! */
2838     n->state = S_CONNECTED;
2839     send_session_ack_message (n);
2840     break;
2841   case S_CONNECTED_SWITCHING_BLACKLIST:
2842     /* duplicate CONNECT_ACK, let's answer by duplciate SESSION_ACK just in case */
2843     send_session_ack_message (n);
2844     break;
2845   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2846     /* new address worked; adopt it and go back to connected! */
2847     n->state = S_CONNECTED;
2848     n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2849     GNUNET_break (GNUNET_NO == n->alternative_address.ats_active);
2850
2851     GST_ats_add_address (n->alternative_address.address, n->alternative_address.session);
2852     set_address (&n->primary_address,
2853                  n->alternative_address.address,
2854                  n->alternative_address.session,
2855                  n->alternative_address.bandwidth_in,
2856                  n->alternative_address.bandwidth_out,
2857                  GNUNET_YES);
2858     free_address (&n->alternative_address);
2859     send_session_ack_message (n);
2860     break;
2861   case S_DISCONNECT:
2862     GNUNET_STATISTICS_update (GST_stats,
2863                               gettext_noop
2864                               ("# unexpected CONNECT_ACK messages (disconnecting)"),
2865                               1, GNUNET_NO);
2866     break;
2867   case S_DISCONNECT_FINISHED:
2868     GNUNET_assert (0);
2869     break;
2870   default:
2871     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2872     GNUNET_break (0);
2873     break;
2874   }
2875 }
2876
2877
2878 /**
2879  * A session was terminated. Take note; if needed, try to get
2880  * an alternative address from ATS.
2881  *
2882  * @param peer identity of the peer where the session died
2883  * @param session session that is gone
2884  * @return GNUNET_YES if this was a session used, GNUNET_NO if
2885  *        this session was not in use
2886  */
2887 int
2888 GST_neighbours_session_terminated (const struct GNUNET_PeerIdentity *peer,
2889                                    struct Session *session)
2890 {
2891   struct NeighbourMapEntry *n;
2892   struct BlackListCheckContext *bcc;
2893   struct BlackListCheckContext *bcc_next;
2894
2895   /* make sure to cancel all ongoing blacklist checks involving 'session' */
2896   bcc_next = bc_head;
2897   while (NULL != (bcc = bcc_next))
2898   {
2899     bcc_next = bcc->next;
2900     if (bcc->na.session == session)
2901     {
2902       GST_blacklist_test_cancel (bcc->bc);
2903       GNUNET_HELLO_address_free (bcc->na.address);
2904       GNUNET_CONTAINER_DLL_remove (bc_head,
2905                                    bc_tail,
2906                                    bcc);
2907       GNUNET_free (bcc);
2908     }
2909   }
2910   if (NULL == (n = lookup_neighbour (peer)))
2911     return GNUNET_NO; /* can't affect us */
2912   if (session != n->primary_address.session)
2913   {
2914     if (session == n->alternative_address.session)
2915     {
2916       free_address (&n->alternative_address);
2917       if ( (S_CONNECTED_SWITCHING_BLACKLIST == n->state) ||
2918            (S_CONNECTED_SWITCHING_CONNECT_SENT == n->state) )
2919         n->state = S_CONNECTED;
2920       else
2921         GNUNET_break (0);
2922     }
2923     return GNUNET_NO; /* doesn't affect us further */
2924   }
2925
2926   n->expect_latency_response = GNUNET_NO;
2927   switch (n->state)
2928   {
2929   case S_NOT_CONNECTED:
2930     GNUNET_break (0);
2931     free_neighbour (n, GNUNET_NO);
2932     return GNUNET_YES;
2933   case S_INIT_ATS:
2934     GNUNET_break (0);
2935     free_neighbour (n, GNUNET_NO);
2936     return GNUNET_YES;
2937   case S_INIT_BLACKLIST:
2938   case S_CONNECT_SENT:
2939     free_address (&n->primary_address);
2940     n->state = S_INIT_ATS;
2941     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
2942     // FIXME: need to ask ATS for suggestions again?
2943     n->suggest_handle = GNUNET_ATS_suggest_address (GST_ats, &n->id);
2944     break;
2945   case S_CONNECT_RECV_BLACKLIST_INBOUND:
2946   case S_CONNECT_RECV_ATS:
2947   case S_CONNECT_RECV_BLACKLIST:
2948   case S_CONNECT_RECV_ACK:
2949     /* error on inbound session; free neighbour entirely */
2950     free_address (&n->primary_address);
2951     free_neighbour (n, GNUNET_NO);
2952     return GNUNET_YES;
2953   case S_CONNECTED:
2954     free_address (&n->primary_address);
2955     n->state = S_RECONNECT_ATS;
2956     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
2957     /* FIXME: is this ATS call needed? */
2958     n->suggest_handle = GNUNET_ATS_suggest_address (GST_ats, &n->id);
2959     break;
2960   case S_RECONNECT_ATS:
2961     /* we don't have an address, how can it go down? */
2962     GNUNET_break (0);
2963     break;
2964   case S_RECONNECT_BLACKLIST:
2965   case S_RECONNECT_SENT:
2966     n->state = S_RECONNECT_ATS;
2967     n->timeout = GNUNET_TIME_relative_to_absolute (ATS_RESPONSE_TIMEOUT);
2968     // FIXME: need to ask ATS for suggestions again?
2969     n->suggest_handle = GNUNET_ATS_suggest_address (GST_ats, &n->id);
2970     break;
2971   case S_CONNECTED_SWITCHING_BLACKLIST:
2972     /* primary went down while we were checking secondary against
2973        blacklist, adopt secondary as primary */
2974     free_address (&n->primary_address);
2975     n->primary_address = n->alternative_address;
2976     memset (&n->alternative_address, 0, sizeof (struct NeighbourAddress));
2977     n->timeout = GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT);
2978     n->state = S_RECONNECT_BLACKLIST;
2979     break;
2980   case S_CONNECTED_SWITCHING_CONNECT_SENT:
2981     /* primary went down while we were waiting for CONNECT_ACK on secondary;
2982        secondary as primary */
2983     free_address (&n->primary_address);
2984     n->primary_address = n->alternative_address;
2985     memset (&n->alternative_address, 0, sizeof (struct NeighbourAddress));
2986     n->timeout = GNUNET_TIME_relative_to_absolute (FAST_RECONNECT_TIMEOUT);
2987     n->state = S_RECONNECT_SENT;
2988     break;
2989   case S_DISCONNECT:
2990     free_address (&n->primary_address);
2991     break;
2992   case S_DISCONNECT_FINISHED:
2993     /* neighbour was freed and plugins told to terminate session */
2994     return GNUNET_NO;
2995     break;
2996   default:
2997     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
2998     GNUNET_break (0);
2999     break;
3000   }
3001   if (GNUNET_SCHEDULER_NO_TASK != n->task)
3002     GNUNET_SCHEDULER_cancel (n->task);
3003   n->task = GNUNET_SCHEDULER_add_now (&master_task, n);
3004   return GNUNET_YES;
3005 }
3006
3007
3008 /**
3009  * We received a 'SESSION_ACK' message from the other peer.
3010  * If we sent a 'CONNECT_ACK' last, this means we are now
3011  * connected.  Otherwise, do nothing.
3012  *
3013  * @param message possibly a 'struct SessionConnectMessage' (check format)
3014  * @param peer identity of the peer to switch the address for
3015  * @param address address of the other peer, NULL if other peer
3016  *                       connected to us
3017  * @param session session to use (or NULL)
3018  */
3019 void
3020 GST_neighbours_handle_session_ack (const struct GNUNET_MessageHeader *message,
3021                                    const struct GNUNET_PeerIdentity *peer,
3022                                    const struct GNUNET_HELLO_Address *address,
3023                                    struct Session *session)
3024 {
3025   struct NeighbourMapEntry *n;
3026
3027   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3028               "Received SESSION_ACK message from peer `%s'\n",
3029               GNUNET_i2s (peer));
3030   if (ntohs (message->size) != sizeof (struct GNUNET_MessageHeader))
3031   {
3032     GNUNET_break_op (0);
3033     return;
3034   }
3035   if (NULL == (n = lookup_neighbour (peer)))
3036     return;
3037   /* check if we are in a plausible state for having sent
3038      a CONNECT_ACK.  If not, return, otherwise break */
3039   if ( ( (S_CONNECT_RECV_ACK != n->state) &&
3040          (S_CONNECT_SENT != n->state) ) ||
3041        (2 != n->send_connect_ack) )
3042   {
3043     GNUNET_STATISTICS_update (GST_stats,
3044                               gettext_noop ("# unexpected SESSION ACK messages"), 1,
3045                               GNUNET_NO);
3046     return;
3047   }
3048   n->state = S_CONNECTED;
3049   n->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
3050   GNUNET_STATISTICS_set (GST_stats,
3051                          gettext_noop ("# peers connected"),
3052                          ++neighbours_connected,
3053                          GNUNET_NO);
3054   connect_notify_cb (callback_cls, &n->id,
3055                      n->primary_address.bandwidth_in,
3056                      n->primary_address.bandwidth_out);
3057
3058   GST_ats_add_address (n->primary_address.address, n->primary_address.session);
3059   set_address (&n->primary_address,
3060                n->primary_address.address,
3061                n->primary_address.session,
3062                n->primary_address.bandwidth_in,
3063                n->primary_address.bandwidth_out,
3064                GNUNET_YES);
3065 }
3066
3067
3068 /**
3069  * Test if we're connected to the given peer.
3070  *
3071  * @param target peer to test
3072  * @return #GNUNET_YES if we are connected, #GNUNET_NO if not
3073  */
3074 int
3075 GST_neighbours_test_connected (const struct GNUNET_PeerIdentity *target)
3076 {
3077   return test_connected (lookup_neighbour (target));
3078 }
3079
3080
3081 /**
3082  * Change the incoming quota for the given peer.
3083  *
3084  * @param neighbour identity of peer to change qutoa for
3085  * @param quota new quota
3086  */
3087 void
3088 GST_neighbours_set_incoming_quota (const struct GNUNET_PeerIdentity *neighbour,
3089                                    struct GNUNET_BANDWIDTH_Value32NBO quota)
3090 {
3091   struct NeighbourMapEntry *n;
3092
3093   if (NULL == (n = lookup_neighbour (neighbour)))
3094   {
3095     GNUNET_STATISTICS_update (GST_stats,
3096                               gettext_noop
3097                               ("# SET QUOTA messages ignored (no such peer)"),
3098                               1, GNUNET_NO);
3099     return;
3100   }
3101   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3102               "Setting inbound quota of %u Bps for peer `%s' to all clients\n",
3103               ntohl (quota.value__), GNUNET_i2s (&n->id));
3104   GNUNET_BANDWIDTH_tracker_update_quota (&n->in_tracker, quota);
3105   if (0 != ntohl (quota.value__))
3106     return;
3107   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting peer `%4s' due to `%s'\n",
3108               GNUNET_i2s (&n->id), "SET_QUOTA");
3109   if (GNUNET_YES == test_connected (n))
3110     GNUNET_STATISTICS_update (GST_stats,
3111                               gettext_noop ("# disconnects due to quota of 0"),
3112                               1, GNUNET_NO);
3113   disconnect_neighbour (n);
3114 }
3115
3116
3117 /**
3118  * We received a disconnect message from the given peer,
3119  * validate and process.
3120  *
3121  * @param peer sender of the message
3122  * @param msg the disconnect message
3123  */
3124 void
3125 GST_neighbours_handle_disconnect_message (const struct GNUNET_PeerIdentity
3126                                           *peer,
3127                                           const struct GNUNET_MessageHeader
3128                                           *msg)
3129 {
3130   struct NeighbourMapEntry *n;
3131   const struct SessionDisconnectMessage *sdm;
3132
3133   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3134               "Received DISCONNECT message from peer `%s'\n",
3135               GNUNET_i2s (peer));
3136   if (ntohs (msg->size) != sizeof (struct SessionDisconnectMessage))
3137   {
3138     // GNUNET_break_op (0);
3139     GNUNET_STATISTICS_update (GST_stats,
3140                               gettext_noop
3141                               ("# disconnect messages ignored (old format)"), 1,
3142                               GNUNET_NO);
3143     return;
3144   }
3145   sdm = (const struct SessionDisconnectMessage *) msg;
3146   if (NULL == (n = lookup_neighbour (peer)))
3147     return;                     /* gone already */
3148   if (GNUNET_TIME_absolute_ntoh (sdm->timestamp).abs_value_us <= n->connect_ack_timestamp.abs_value_us)
3149   {
3150     GNUNET_STATISTICS_update (GST_stats,
3151                               gettext_noop
3152                               ("# disconnect messages ignored (timestamp)"), 1,
3153                               GNUNET_NO);
3154     return;
3155   }
3156   if (0 != memcmp (peer, &sdm->public_key, sizeof (struct GNUNET_PeerIdentity)))
3157   {
3158     GNUNET_break_op (0);
3159     return;
3160   }
3161   if (ntohl (sdm->purpose.size) !=
3162       sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
3163       sizeof (struct GNUNET_CRYPTO_EddsaPublicKey) +
3164       sizeof (struct GNUNET_TIME_AbsoluteNBO))
3165   {
3166     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3167                 "%s message from peer `%s' has invalid size \n",
3168                 "DISCONNECT",
3169                 GNUNET_i2s (peer));
3170     GNUNET_break_op (0);
3171     return;
3172   }
3173   if (GNUNET_OK !=
3174       GNUNET_CRYPTO_eddsa_verify
3175       (GNUNET_MESSAGE_TYPE_TRANSPORT_SESSION_DISCONNECT, &sdm->purpose,
3176        &sdm->signature, &sdm->public_key))
3177   {
3178     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3179                 "%s message from peer `%s' cannot be verified \n",
3180                 "DISCONNECT",
3181                 GNUNET_i2s (peer));
3182     GNUNET_break_op (0);
3183     return;
3184   }
3185   if (GNUNET_YES == test_connected (n))
3186     GNUNET_STATISTICS_update (GST_stats,
3187                               gettext_noop
3188                               ("# other peer asked to disconnect from us"), 1,
3189                               GNUNET_NO);
3190   disconnect_neighbour (n);
3191 }
3192
3193
3194 /**
3195  * Closure for the neighbours_iterate function.
3196  */
3197 struct IteratorContext
3198 {
3199   /**
3200    * Function to call on each connected neighbour.
3201    */
3202   GST_NeighbourIterator cb;
3203
3204   /**
3205    * Closure for 'cb'.
3206    */
3207   void *cb_cls;
3208 };
3209
3210
3211 /**
3212  * Call the callback from the closure for each connected neighbour.
3213  *
3214  * @param cls the 'struct IteratorContext'
3215  * @param key the hash of the public key of the neighbour
3216  * @param value the 'struct NeighbourMapEntry'
3217  * @return GNUNET_OK (continue to iterate)
3218  */
3219 static int
3220 neighbours_iterate (void *cls, const struct GNUNET_PeerIdentity * key, void *value)
3221 {
3222   struct IteratorContext *ic = cls;
3223   struct NeighbourMapEntry *n = value;
3224
3225   if (GNUNET_YES == test_connected (n))
3226   {
3227     struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in;
3228     struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out;
3229
3230     if (NULL != n->primary_address.address)
3231     {
3232       bandwidth_in = n->primary_address.bandwidth_in;
3233       bandwidth_out = n->primary_address.bandwidth_out;
3234     }
3235     else
3236     {
3237       bandwidth_in = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
3238       bandwidth_out = GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT;
3239     }
3240
3241     ic->cb (ic->cb_cls, &n->id,
3242             n->primary_address.address,
3243             bandwidth_in, bandwidth_out);
3244   }
3245   return GNUNET_OK;
3246 }
3247
3248
3249 /**
3250  * Iterate over all connected neighbours.
3251  *
3252  * @param cb function to call
3253  * @param cb_cls closure for cb
3254  */
3255 void
3256 GST_neighbours_iterate (GST_NeighbourIterator cb, void *cb_cls)
3257 {
3258   struct IteratorContext ic;
3259
3260   if (NULL == neighbours)
3261     return; /* can happen during shutdown */
3262   ic.cb = cb;
3263   ic.cb_cls = cb_cls;
3264   GNUNET_CONTAINER_multipeermap_iterate (neighbours, &neighbours_iterate, &ic);
3265 }
3266
3267
3268 /**
3269  * If we have an active connection to the given target, it must be shutdown.
3270  *
3271  * @param target peer to disconnect from
3272  */
3273 void
3274 GST_neighbours_force_disconnect (const struct GNUNET_PeerIdentity *target)
3275 {
3276   struct NeighbourMapEntry *n;
3277
3278   if (NULL == (n = lookup_neighbour (target)))
3279     return;  /* not active */
3280   if (GNUNET_YES == test_connected (n))
3281     GNUNET_STATISTICS_update (GST_stats,
3282                               gettext_noop
3283                               ("# disconnected from peer upon explicit request"), 1,
3284                               GNUNET_NO);
3285   disconnect_neighbour (n);
3286 }
3287
3288
3289 /**
3290  * Obtain current latency information for the given neighbour.
3291  *
3292  * @param peer to get the latency for
3293  * @return observed latency of the address, FOREVER if the
3294  *         the connection is not up
3295  */
3296 struct GNUNET_TIME_Relative
3297 GST_neighbour_get_latency (const struct GNUNET_PeerIdentity *peer)
3298 {
3299   struct NeighbourMapEntry *n;
3300
3301   n = lookup_neighbour (peer);
3302   if (NULL == n)
3303     return GNUNET_TIME_UNIT_FOREVER_REL;
3304   switch (n->state)
3305   {
3306   case S_CONNECTED:
3307   case S_CONNECTED_SWITCHING_CONNECT_SENT:
3308   case S_CONNECTED_SWITCHING_BLACKLIST:
3309   case S_RECONNECT_SENT:
3310   case S_RECONNECT_ATS:
3311   case S_RECONNECT_BLACKLIST:
3312     return n->latency;
3313   case S_NOT_CONNECTED:
3314   case S_INIT_BLACKLIST:
3315   case S_INIT_ATS:
3316   case S_CONNECT_RECV_BLACKLIST_INBOUND:
3317   case S_CONNECT_RECV_ATS:
3318   case S_CONNECT_RECV_BLACKLIST:
3319   case S_CONNECT_RECV_ACK:
3320   case S_CONNECT_SENT:
3321   case S_DISCONNECT:
3322   case S_DISCONNECT_FINISHED:
3323     return GNUNET_TIME_UNIT_FOREVER_REL;
3324   default:
3325     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unhandled state `%s' \n",print_state (n->state));
3326     GNUNET_break (0);
3327     break;
3328   }
3329   return GNUNET_TIME_UNIT_FOREVER_REL;
3330 }
3331
3332
3333 /**
3334  * Obtain current address information for the given neighbour.
3335  *
3336  * @param peer
3337  * @return address currently used
3338  */
3339 struct GNUNET_HELLO_Address *
3340 GST_neighbour_get_current_address (const struct GNUNET_PeerIdentity *peer)
3341 {
3342   struct NeighbourMapEntry *n;
3343
3344   n = lookup_neighbour (peer);
3345   if (NULL == n)
3346     return NULL;
3347   return n->primary_address.address;
3348 }
3349
3350
3351 /**
3352  * Initialize the neighbours subsystem.
3353  *
3354  * @param cls closure for callbacks
3355  * @param connect_cb function to call if we connect to a peer
3356  * @param disconnect_cb function to call if we disconnect from a peer
3357  * @param peer_address_cb function to call if we change an active address
3358  *                   of a neighbour
3359  * @param max_fds maximum number of fds to use
3360  */
3361 void
3362 GST_neighbours_start (void *cls,
3363                                                                         NotifyConnect connect_cb,
3364                       GNUNET_TRANSPORT_NotifyDisconnect disconnect_cb,
3365                       GNUNET_TRANSPORT_PeerIterateCallback peer_address_cb,
3366                       unsigned int max_fds)
3367 {
3368   callback_cls = cls;
3369   connect_notify_cb = connect_cb;
3370   disconnect_notify_cb = disconnect_cb;
3371   address_change_cb = peer_address_cb;
3372   neighbours = GNUNET_CONTAINER_multipeermap_create (NEIGHBOUR_TABLE_SIZE, GNUNET_NO);
3373   util_transmission_tk = GNUNET_SCHEDULER_add_delayed (UTIL_TRANSMISSION_INTERVAL,
3374       utilization_transmission, NULL);
3375 }
3376
3377
3378 /**
3379  * Disconnect from the given neighbour.
3380  *
3381  * @param cls unused
3382  * @param key hash of neighbour's public key (not used)
3383  * @param value the 'struct NeighbourMapEntry' of the neighbour
3384  * @return GNUNET_OK (continue to iterate)
3385  */
3386 static int
3387 disconnect_all_neighbours (void *cls,
3388                            const struct GNUNET_PeerIdentity *key,
3389                            void *value)
3390 {
3391   struct NeighbourMapEntry *n = value;
3392
3393   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3394               "Disconnecting peer `%4s', %s\n",
3395               GNUNET_i2s (&n->id), "SHUTDOWN_TASK");
3396   n->state = S_DISCONNECT_FINISHED;
3397   free_neighbour (n, GNUNET_NO);
3398   return GNUNET_OK;
3399 }
3400
3401
3402 /**
3403  * Cleanup the neighbours subsystem.
3404  */
3405 void
3406 GST_neighbours_stop ()
3407 {
3408   if (NULL == neighbours)
3409     return;
3410   if (GNUNET_SCHEDULER_NO_TASK != util_transmission_tk)
3411   {
3412     GNUNET_SCHEDULER_cancel (util_transmission_tk);
3413     util_transmission_tk = GNUNET_SCHEDULER_NO_TASK;
3414   }
3415
3416   GNUNET_CONTAINER_multipeermap_iterate (neighbours,
3417                                          &disconnect_all_neighbours,
3418                                          NULL);
3419   GNUNET_CONTAINER_multipeermap_destroy (neighbours);
3420   neighbours = NULL;
3421   callback_cls = NULL;
3422   connect_notify_cb = NULL;
3423   disconnect_notify_cb = NULL;
3424   address_change_cb = NULL;
3425 }
3426
3427
3428 /* end of file gnunet-service-transport_neighbours.c */