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