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