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