-fix docu
[oweals/gnunet.git] / src / core / gnunet-service-core_kx.c
index 8f6d19652f5e3242845570d96853cd7d7e5b308b..0cc3521acc9220ed6e795b9b94fce91c62808c3b 100644 (file)
  */
 #include "platform.h"
 #include "gnunet-service-core_kx.h"
+#include "gnunet-service-core.h"
+#include "gnunet-service-core_clients.h"
 #include "gnunet-service-core_neighbours.h"
+#include "gnunet-service-core_sessions.h"
+#include "gnunet_statistics_service.h"
+#include "gnunet_peerinfo_service.h"
+#include "gnunet_hello_lib.h"
+#include "gnunet_constants.h"
+#include "gnunet_signatures.h"
+#include "gnunet_protocols.h"
+#include "core.h"
 
 
+/**
+ * How long do we wait for SET_KEY confirmation initially?
+ */
+#define INITIAL_SET_KEY_RETRY_FREQUENCY GNUNET_TIME_relative_multiply (MAX_SET_KEY_DELAY, 1)
+
+/**
+ * What is the minimum frequency for a PING message?
+ */
+#define MIN_PING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
+
+/**
+ * How often do we rekey?
+ */
+#define REKEY_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 90)
+
+
+/**
+ * What is the maximum age of a message for us to consider processing
+ * it?  Note that this looks at the timestamp used by the other peer,
+ * so clock skew between machines does come into play here.  So this
+ * should be picked high enough so that a little bit of clock skew
+ * does not prevent peers from connecting to us.
+ */
+#define MAX_MESSAGE_AGE GNUNET_TIME_UNIT_DAYS
+
+/**
+ * What is the maximum delay for a SET_KEY message?
+ */
+#define MAX_SET_KEY_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
+
+
+GNUNET_NETWORK_STRUCT_BEGIN
+
 /**
  * We're sending an (encrypted) PING to the other peer to check if he
  * can decrypt.  The other peer should respond with a PONG with the
@@ -59,8 +102,7 @@ struct PingMessage
 
 
 /**
- * Response to a PING.  Includes data from the original PING
- * plus initial bandwidth quota information.
+ * Response to a PING.  Includes data from the original PING.
  */
 struct PongMessage
 {
@@ -81,10 +123,9 @@ struct PongMessage
   uint32_t challenge GNUNET_PACKED;
 
   /**
-   * Desired bandwidth (how much we should send to this
-   * peer / how much is the sender willing to receive).
+   * Reserved, always 'GNUNET_BANDWIDTH_VALUE_MAX'.
    */
-  struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
+  struct GNUNET_BANDWIDTH_Value32NBO reserved;
 
   /**
    * Intended target of the PING, used primarily to check
@@ -170,10 +211,9 @@ struct EncryptedMessage
   uint32_t sequence_number GNUNET_PACKED;
 
   /**
-   * Desired bandwidth (how much we should send to this peer / how
-   * much is the sender willing to receive)?
+   * Reserved, always 'GNUNET_BANDWIDTH_VALUE_MAX'.
    */
-  struct GNUNET_BANDWIDTH_Value32NBO inbound_bw_limit;
+  struct GNUNET_BANDWIDTH_Value32NBO reserved;
 
   /**
    * Timestamp.  Used to prevent reply of ancient messages
@@ -182,6 +222,14 @@ struct EncryptedMessage
   struct GNUNET_TIME_AbsoluteNBO timestamp;
 
 };
+GNUNET_NETWORK_STRUCT_END
+
+
+/**
+ * Number of bytes (at the beginning) of "struct EncryptedMessage"
+ * that are NOT encrypted.
+ */
+#define ENCRYPTED_HEADER_SIZE (offsetof(struct EncryptedMessage, sequence_number))
 
 
 /**
@@ -214,7 +262,19 @@ enum KxStateMachine
    * encrypted with his session key (which we got).  Key exchange
    * is done.
    */
-  KX_STATE_UP
+  KX_STATE_UP,
+
+  /**
+   * We're rekeying, so we have received the other peer's session
+   * key, but he didn't get ours yet.
+   */
+  KX_STATE_REKEY,
+
+  /**
+   * We're rekeying but have not yet received confirmation for our new
+   * key from the other peer.
+   */
+  KX_STATE_REKEY_SENT
 };
 
 
@@ -256,6 +316,12 @@ struct GSC_KeyExchangeInfo
    */
   struct PongMessage *pong_received;
 
+  /**
+   * Encrypted message we received from the other peer and
+   * did not process yet (or NULL).
+   */
+  struct EncryptedMessage *emsg_received;
+
   /**
    * Non-NULL if we are currently looking up HELLOs for this peer.
    * for this peer.
@@ -316,6 +382,23 @@ struct GSC_KeyExchangeInfo
    */
   GNUNET_SCHEDULER_TaskIdentifier keep_alive_task;
 
+  /**
+   * Bit map indicating which of the 32 sequence numbers before the last
+   * were received (good for accepting out-of-order packets and
+   * estimating reliability of the connection)
+   */
+  unsigned int last_packets_bitmap;
+
+  /**
+   * last sequence number received on this connection (highest)
+   */
+  uint32_t last_sequence_number_received;
+
+  /**
+   * last sequence number transmitted
+   */
+  uint32_t last_sequence_number_sent;
+
   /**
    * What was our PING challenge number (for this peer)?
    */
@@ -329,7 +412,6 @@ struct GSC_KeyExchangeInfo
 };
 
 
-
 /**
  * Handle to peerinfo service.
  */
@@ -351,9 +433,13 @@ static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
 static struct GNUNET_SERVER_MessageStreamTokenizer *mst;
 
 
-
 /**
  * Derive an authentication key from "set key" information
+ *
+ * @param akey authentication key to derive
+ * @param skey session key to use
+ * @param seed seed to use
+ * @param creation_time creation time to use
  */
 static void
 derive_auth_key (struct GNUNET_CRYPTO_AuthKey *akey,
@@ -363,7 +449,6 @@ derive_auth_key (struct GNUNET_CRYPTO_AuthKey *akey,
   static const char ctx[] = "authentication key";
   struct GNUNET_TIME_AbsoluteNBO ctbe;
 
-
   ctbe = GNUNET_TIME_absolute_hton (creation_time);
   GNUNET_CRYPTO_hmac_derive_key (akey, skey, &seed, sizeof (seed), &skey->key,
                                  sizeof (skey->key), &ctbe, sizeof (ctbe), ctx,
@@ -373,6 +458,11 @@ derive_auth_key (struct GNUNET_CRYPTO_AuthKey *akey,
 
 /**
  * Derive an IV from packet information
+ *
+ * @param iv initialization vector to initialize
+ * @param skey session key to use
+ * @param seed seed to use
+ * @param identity identity of the other peer to use
  */
 static void
 derive_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
@@ -387,8 +477,15 @@ derive_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
                                sizeof (ctx), NULL);
 }
 
+
 /**
  * Derive an IV from pong packet information
+ *
+ * @param iv initialization vector to initialize
+ * @param skey session key to use
+ * @param seed seed to use
+ * @param challenge nonce to use
+ * @param identity identity of the other peer to use
  */
 static void
 derive_pong_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
@@ -428,22 +525,22 @@ do_encrypt (struct GSC_KeyExchangeInfo *kx,
   GNUNET_assert (size ==
                  GNUNET_CRYPTO_aes_encrypt (in, (uint16_t) size,
                                             &kx->encrypt_key, iv, out));
-  GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes encrypted"), size,
+  GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# bytes encrypted"), size,
                             GNUNET_NO);
-#if DEBUG_CORE > 2
+  /* the following is too sensitive to write to log files by accident,
+     so we require manual intervention to get this one... */
+#if 0
   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
               "Encrypted %u bytes for `%4s' using key %u, IV %u\n",
               (unsigned int) size, GNUNET_i2s (&kx->peer),
               (unsigned int) kx->encrypt_key.crc32, GNUNET_CRYPTO_crc32_n (iv,
-                                                                          sizeof
-                                                                          (iv)));
+                                                                           sizeof
+                                                                           (iv)));
 #endif
   return GNUNET_OK;
 }
 
 
-
-
 /**
  * Decrypt size bytes from in and write the result to out.  Use the
  * key for inbound traffic of the given neighbour.  This function does
@@ -466,32 +563,44 @@ do_decrypt (struct GSC_KeyExchangeInfo *kx,
     GNUNET_break (0);
     return GNUNET_NO;
   }
-  if ((kx->status != KX_STATE_KEY_RECEIVED) &&
-      (kx->status != KX_STATE_UP))
+  if ( (kx->status != KX_STATE_KEY_RECEIVED) && (kx->status != KX_STATE_UP) &&
+       (kx->status != KX_STATE_REKEY_SENT) &&
+       (kx->status != KX_STATE_REKEY) )
   {
     GNUNET_break_op (0);
     return GNUNET_SYSERR;
   }
   if (size !=
-      GNUNET_CRYPTO_aes_decrypt (in, (uint16_t) size, &kx->decrypt_key, iv, out))
+      GNUNET_CRYPTO_aes_decrypt (in, (uint16_t) size, &kx->decrypt_key, iv,
+                                 out))
   {
     GNUNET_break (0);
     return GNUNET_SYSERR;
   }
-  GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes decrypted"), size,
+  GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# bytes decrypted"), size,
                             GNUNET_NO);
-#if DEBUG_CORE > 1
+  /* the following is too sensitive to write to log files by accident,
+     so we require manual intervention to get this one... */
+#if 0
   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
               "Decrypted %u bytes from `%4s' using key %u, IV %u\n",
               (unsigned int) size, GNUNET_i2s (&kx->peer),
               (unsigned int) kx->decrypt_key.crc32, GNUNET_CRYPTO_crc32_n (iv,
-                                                                          sizeof
-                                                                          (*iv)));
+                                                                           sizeof
+                                                                           (*iv)));
 #endif
   return GNUNET_OK;
 }
 
 
+/**
+ * Send our key (and encrypted PING) to the other peer.
+ *
+ * @param kx key exchange context
+ */
+static void
+send_key (struct GSC_KeyExchangeInfo *kx);
+
 
 /**
  * Task that will retry "send_key" if our previous attempt failed.
@@ -505,7 +614,8 @@ set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
   struct GSC_KeyExchangeInfo *kx = cls;
 
   kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
-  kx->set_key_retry_frequency = GNUNET_TIME_relative_multiply (kx->set_key_retry_frequency, 2);
+  kx->set_key_retry_frequency =
+      GNUNET_TIME_relative_multiply (kx->set_key_retry_frequency, 2);
   send_key (kx);
 }
 
@@ -522,37 +632,40 @@ set_key_retry_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
  */
 static void
 process_hello (void *cls, const struct GNUNET_PeerIdentity *peer,
-              const struct GNUNET_HELLO_Message *hello,
-              const char *err_msg)
+               const struct GNUNET_HELLO_Message *hello, const char *err_msg)
 {
   struct GSC_KeyExchangeInfo *kx = cls;
   struct SetKeyMessage *skm;
 
-  GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == n->retry_set_key_task);
   if (err_msg != NULL)
   {
     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                 _("Error in communication with PEERINFO service\n"));
     kx->pitr = NULL;
+    if (GNUNET_SCHEDULER_NO_TASK != kx->retry_set_key_task)
+      GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
+    kx->retry_set_key_task =
+        GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
+                                      &set_key_retry_task, kx);
     return;
   }
   if (peer == NULL)
   {
     kx->pitr = NULL;
     if (kx->public_key != NULL)
-      return; /* done here */
-#if DEBUG_CORE
+      return;                   /* done here */
     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
-               "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
-               GNUNET_i2s (&kx->peer));
-#endif
-    GNUNET_STATISTICS_update (stats,
-                             gettext_noop
-                             ("# Delayed connecting due to lack of public key"),
-                             1, GNUNET_NO);
+                "Failed to obtain public key for peer `%4s', delaying processing of SET_KEY\n",
+                GNUNET_i2s (&kx->peer));
+    GNUNET_STATISTICS_update (GSC_stats,
+                              gettext_noop
+                              ("# Delayed connecting due to lack of public key"),
+                              1, GNUNET_NO);
+    if (GNUNET_SCHEDULER_NO_TASK != kx->retry_set_key_task)
+      GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
     kx->retry_set_key_task =
-      GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
-                                   &set_key_retry_task, kx);
+        GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
+                                      &set_key_retry_task, kx);
     return;
   }
   if (kx->public_key != NULL)
@@ -561,9 +674,10 @@ process_hello (void *cls, const struct GNUNET_PeerIdentity *peer,
     GNUNET_break (0);
     return;
   }
+  GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == kx->retry_set_key_task);
   kx->public_key =
       GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
-  if (GNUNET_OK != GNUNET_HELLO_get_key (hello, n->public_key))
+  if (GNUNET_OK != GNUNET_HELLO_get_key (hello, kx->public_key))
   {
     GNUNET_break (0);
     GNUNET_free (kx->public_key);
@@ -581,15 +695,6 @@ process_hello (void *cls, const struct GNUNET_PeerIdentity *peer,
 }
 
 
-/**
- * Send our key (and encrypted PING) to the other peer.
- *
- * @param kx key exchange context
- */
-static void
-send_key (struct GSC_KeyExchangeInfo *kx);
-
-
 /**
  * Start the key exchange with the given peer.
  *
@@ -601,14 +706,18 @@ GSC_KX_start (const struct GNUNET_PeerIdentity *pid)
 {
   struct GSC_KeyExchangeInfo *kx;
 
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Initiating key exchange with `%s'\n",
+              GNUNET_i2s (pid));
+  GNUNET_STATISTICS_update (GSC_stats,
+                            gettext_noop ("# key exchanges initiated"), 1,
+                            GNUNET_NO);
   kx = GNUNET_malloc (sizeof (struct GSC_KeyExchangeInfo));
   kx->peer = *pid;
-  n->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
-  kx->pitr = GNUNET_PEERINFO_iterate (peerinfo,
-                                     pid,
-                                     GNUNET_TIME_UNIT_FOREVER_REL /* timeout? */,
-                                     &process_hello,
-                                     kx);  
+  kx->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
+  kx->pitr =
+      GNUNET_PEERINFO_iterate (peerinfo, pid,
+                               GNUNET_TIME_UNIT_FOREVER_REL /* timeout? */ ,
+                               &process_hello, kx);
   return kx;
 }
 
@@ -621,6 +730,8 @@ GSC_KX_start (const struct GNUNET_PeerIdentity *pid)
 void
 GSC_KX_stop (struct GSC_KeyExchangeInfo *kx)
 {
+  GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# key exchanges stopped"),
+                            1, GNUNET_NO);
   if (kx->pitr != NULL)
   {
     GNUNET_PEERINFO_iterate_cancel (kx->pitr);
@@ -633,12 +744,13 @@ GSC_KX_stop (struct GSC_KeyExchangeInfo *kx)
   }
   if (kx->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
   {
-    GNUNET_SCHEDULER_cancel (n->keep_alive_task);
+    GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
     kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
   }
   GNUNET_free_non_null (kx->skm_received);
   GNUNET_free_non_null (kx->ping_received);
   GNUNET_free_non_null (kx->pong_received);
+  GNUNET_free_non_null (kx->emsg_received);
   GNUNET_free_non_null (kx->public_key);
   GNUNET_free (kx);
 }
@@ -653,44 +765,42 @@ GSC_KX_stop (struct GSC_KeyExchangeInfo *kx)
  */
 void
 GSC_KX_handle_set_key (struct GSC_KeyExchangeInfo *kx,
-                      const struct GNUNET_MessageHandler *msg)
+                       const struct GNUNET_MessageHeader *msg)
 {
   const struct SetKeyMessage *m;
-  struct SetKeyMessage *m_cpy;
   struct GNUNET_TIME_Absolute t;
   struct GNUNET_CRYPTO_AesSessionKey k;
   struct PingMessage *ping;
   struct PongMessage *pong;
-  enum PeerStateMachine sender_status;
+  enum KxStateMachine sender_status;
   uint16_t size;
-  
-  size = ntohs (msg->header);
+
+  size = ntohs (msg->size);
   if (size != sizeof (struct SetKeyMessage))
-    {
-      GNUNET_break_op (0);
-      return;
-    }
-  m = (const struct SetKeyMessage*) msg;
-  GNUNET_STATISTICS_update (stats, gettext_noop ("# session keys received"),
-                           1, GNUNET_NO);
+  {
+    GNUNET_break_op (0);
+    return;
+  }
+  m = (const struct SetKeyMessage *) msg;
+  GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# session keys received"),
+                            1, GNUNET_NO);
 
-#if DEBUG_CORE
   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
               "Core service receives `%s' request from `%4s'.\n", "SET_KEY",
               GNUNET_i2s (&kx->peer));
-#endif
   if (kx->public_key == NULL)
   {
     GNUNET_free_non_null (kx->skm_received);
-    kx->skm_received = GNUNET_copy_message (msg);
+    kx->skm_received = (struct SetKeyMessage *) GNUNET_copy_message (msg);
     return;
   }
   if (0 !=
-      memcmp (&m->target, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
+      memcmp (&m->target, &GSC_my_identity,
+              sizeof (struct GNUNET_PeerIdentity)))
   {
     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
-                _("`%s' is for `%s', not for me.  Ignoring.\n"),
-                "SET_KEY", GNUNET_i2s (&m->target));
+                _("`%s' is for `%s', not for me.  Ignoring.\n"), "SET_KEY",
+                GNUNET_i2s (&m->target));
     return;
   }
   if ((ntohl (m->purpose.size) !=
@@ -707,8 +817,7 @@ GSC_KX_handle_set_key (struct GSC_KeyExchangeInfo *kx,
     return;
   }
   t = GNUNET_TIME_absolute_ntoh (m->creation_time);
-  if (((kx->status == KX_STATE_KEY_RECEIVED) ||
-       (kx->status == KX_STATE_UP)) &&
+  if (((kx->status == KX_STATE_KEY_RECEIVED) || (kx->status == KX_STATE_UP)) &&
       (t.abs_value < kx->decrypt_key_created.abs_value))
   {
     /* this could rarely happen due to massive re-ordering of
@@ -727,9 +836,11 @@ GSC_KX_handle_set_key (struct GSC_KeyExchangeInfo *kx,
     GNUNET_break_op (0);
     return;
   }
-  GNUNET_STATISTICS_update (stats,
+  GNUNET_STATISTICS_update (GSC_stats,
                             gettext_noop ("# SET_KEY messages decrypted"), 1,
                             GNUNET_NO);
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received SET_KEY from `%s'\n",
+              GNUNET_i2s (&kx->peer));
   kx->decrypt_key = k;
   if (kx->decrypt_key_created.abs_value != t.abs_value)
   {
@@ -738,25 +849,34 @@ GSC_KX_handle_set_key (struct GSC_KeyExchangeInfo *kx,
     kx->last_packets_bitmap = 0;
     kx->decrypt_key_created = t;
   }
-  sender_status = (enum PeerStateMachine) ntohl (m->sender_status);
-
+  sender_status = (enum KxStateMachine) ntohl (m->sender_status);
   switch (kx->status)
   {
   case KX_STATE_DOWN:
-    kx->status = PEER_STATE_KEY_RECEIVED;
+    kx->status = KX_STATE_KEY_RECEIVED;
     /* we're not up, so we are already doing 'send_key' */
     break;
   case KX_STATE_KEY_SENT:
-    n->status = PEER_STATE_KEY_RECEIVED;
+    kx->status = KX_STATE_KEY_RECEIVED;
     /* we're not up, so we are already doing 'send_key' */
     break;
   case KX_STATE_KEY_RECEIVED:
     /* we're not up, so we are already doing 'send_key' */
     break;
-  case KX_STATE_UP:
-    if ( (sender_status == KX_STATE_DOWN) ||
-        (sender_status == KX_PEER_STATE_KEY_SENT) )
-      send_key (kx); /* we are up, but other peer is not! */
+  case KX_STATE_UP: 
+    if ((sender_status == KX_STATE_DOWN) ||
+        (sender_status == KX_STATE_KEY_SENT))
+      send_key (kx);            /* we are up, but other peer is not! */
+    break;
+  case KX_STATE_REKEY:
+    if ((sender_status == KX_STATE_DOWN) ||
+        (sender_status == KX_STATE_KEY_SENT))
+      send_key (kx);            /* we are up, but other peer is not! */
+    break;
+  case KX_STATE_REKEY_SENT:
+    if ((sender_status == KX_STATE_DOWN) ||
+        (sender_status == KX_STATE_KEY_SENT))
+      send_key (kx);            /* we are up, but other peer is not! */
     break;
   default:
     GNUNET_break (0);
@@ -787,7 +907,8 @@ GSC_KX_handle_set_key (struct GSC_KeyExchangeInfo *kx,
  * @param msg the encrypted PING message itself
  */
 void
-GSC_KX_handle_ping (struct GSC_KeyExchangeInfo *n, const struct GNUNET_MessageHeader *msg)
+GSC_KX_handle_ping (struct GSC_KeyExchangeInfo *kx,
+                    const struct GNUNET_MessageHeader *msg)
 {
   const struct PingMessage *m;
   struct PingMessage t;
@@ -798,27 +919,25 @@ GSC_KX_handle_ping (struct GSC_KeyExchangeInfo *n, const struct GNUNET_MessageHe
 
   msize = ntohs (msg->size);
   if (msize != sizeof (struct PingMessage))
-    {
-      GNUNET_break_op (0);
-      return;
-    }
-  GNUNET_STATISTICS_update (GSC_stats, 
-                           gettext_noop ("# PING messages received"),
-                           1, GNUNET_NO);
-  if ( (kx->status != KX_STATE_KEY_RECEIVED) &&
-       (kx->status != KX_STATE_UP) )
-    {
-      /* defer */
-      GNUNET_free_non_null (n->pending_ping);
-      n->pending_ping = GNUNET_copy_message (msg);
-      return;
-    }
-  m = (const struct PingMessage*) msg;
-#if DEBUG_CORE
+  {
+    GNUNET_break_op (0);
+    return;
+  }
+  GNUNET_STATISTICS_update (GSC_stats,
+                            gettext_noop ("# PING messages received"), 1,
+                            GNUNET_NO);
+  if ((kx->status != KX_STATE_KEY_RECEIVED) && (kx->status != KX_STATE_UP) &&
+      (kx->status != KX_STATE_REKEY_SENT))
+  {
+    /* defer */
+    GNUNET_free_non_null (kx->ping_received);
+    kx->ping_received = (struct PingMessage *) GNUNET_copy_message (msg);
+    return;
+  }
+  m = (const struct PingMessage *) msg;
   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
               "Core service receives `%s' request from `%4s'.\n", "PING",
-              GNUNET_i2s (&n->peer));
-#endif
+              GNUNET_i2s (&kx->peer));
   derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity);
   if (GNUNET_OK !=
       do_decrypt (kx, &iv, &m->target, &t.target,
@@ -834,32 +953,33 @@ GSC_KX_handle_ping (struct GSC_KeyExchangeInfo *n, const struct GNUNET_MessageHe
     char sender[9];
     char peer[9];
 
-    GNUNET_snprintf (sender, sizeof (sender), "%8s", GNUNET_i2s (&n->peer));
+    GNUNET_snprintf (sender, sizeof (sender), "%8s", GNUNET_i2s (&kx->peer));
     GNUNET_snprintf (peer, sizeof (peer), "%8s", GNUNET_i2s (&t.target));
     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
-                _("Received PING from `%s' for different identity: I am `%s', PONG identity: `%s'\n"),
-                sender, GNUNET_i2s (&my_identity), peer);
+                _
+                ("Received PING from `%s' for different identity: I am `%s', PONG identity: `%s'\n"),
+                sender, GNUNET_i2s (&GSC_my_identity), peer);
     GNUNET_break_op (0);
     return;
   }
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received PING from `%s'\n",
+              GNUNET_i2s (&kx->peer));
   /* construct PONG */
-  tx.inbound_bw_limit = n->bw_in;
+  tx.reserved = GNUNET_BANDWIDTH_VALUE_MAX;
   tx.challenge = t.challenge;
   tx.target = t.target;
   tp.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PONG);
   tp.header.size = htons (sizeof (struct PongMessage));
   tp.iv_seed =
       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
-  derive_pong_iv (&iv, &n->encrypt_key, tp.iv_seed, t.challenge, &kx->peer);
-  do_encrypt (n, &iv, &tx.challenge, &tp.challenge,
+  derive_pong_iv (&iv, &kx->encrypt_key, tp.iv_seed, t.challenge, &kx->peer);
+  do_encrypt (kx, &iv, &tx.challenge, &tp.challenge,
               sizeof (struct PongMessage) - ((void *) &tp.challenge -
-                                             (void *) tp));
-  GNUNET_STATISTICS_update (GSC_stats, 
-                           gettext_noop ("# PONG messages created"), 1,
-                            GNUNET_NO);
-  GSC_NEIGHBOURS_transmit (&kx->peer,
-                          &tp.header,
-                          GNUNET_TIME_UNIT_FOREVER_REL /* FIXME: timeout */);
+                                             (void *) &tp));
+  GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# PONG messages created"),
+                            1, GNUNET_NO);
+  GSC_NEIGHBOURS_transmit (&kx->peer, &tp.header,
+                           GNUNET_TIME_UNIT_FOREVER_REL /* FIXME: timeout */ );
 }
 
 
@@ -880,21 +1000,22 @@ setup_fresh_setkey (struct GSC_KeyExchangeInfo *kx)
   skm->header.size = htons (sizeof (struct SetKeyMessage));
   skm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_SET_KEY);
   skm->purpose.size =
-    htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
-          sizeof (struct GNUNET_TIME_AbsoluteNBO) +
-          sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
-          sizeof (struct GNUNET_PeerIdentity));
+      htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
+             sizeof (struct GNUNET_TIME_AbsoluteNBO) +
+             sizeof (struct GNUNET_CRYPTO_RsaEncryptedData) +
+             sizeof (struct GNUNET_PeerIdentity));
   skm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_KEY);
   skm->creation_time = GNUNET_TIME_absolute_hton (kx->encrypt_key_created);
   skm->target = kx->peer;
   GNUNET_assert (GNUNET_OK ==
-                GNUNET_CRYPTO_rsa_encrypt (&kx->encrypt_key,
-                                           sizeof (struct
-                                                   GNUNET_CRYPTO_AesSessionKey),
-                                           kx->public_key, &skm->encrypted_key));
+                 GNUNET_CRYPTO_rsa_encrypt (&kx->encrypt_key,
+                                            sizeof (struct
+                                                    GNUNET_CRYPTO_AesSessionKey),
+                                            kx->public_key,
+                                            &skm->encrypted_key));
   GNUNET_assert (GNUNET_OK ==
-                GNUNET_CRYPTO_rsa_sign (my_private_key, &skm->purpose,
-                                        &skm->signature));
+                 GNUNET_CRYPTO_rsa_sign (my_private_key, &skm->purpose,
+                                         &skm->signature));
 }
 
 
@@ -908,18 +1029,19 @@ setup_fresh_ping (struct GSC_KeyExchangeInfo *kx)
 {
   struct PingMessage pp;
   struct PingMessage *pm;
+  struct GNUNET_CRYPTO_AesInitializationVector iv;
 
   pm = &kx->ping;
   pm->header.size = htons (sizeof (struct PingMessage));
   pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING);
   pm->iv_seed =
-    GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
+      GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
   derive_iv (&iv, &kx->encrypt_key, pm->iv_seed, &kx->peer);
   pp.challenge = kx->ping_challenge;
   pp.target = kx->peer;
   do_encrypt (kx, &iv, &pp.target, &pm->target,
-             sizeof (struct PingMessage) - ((void *) &pm->target -
-                                            (void *) pm));
+              sizeof (struct PingMessage) - ((void *) &pm->target -
+                                             (void *) pm));
 }
 
 
@@ -940,21 +1062,91 @@ send_keep_alive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
   kx->keep_alive_task = GNUNET_SCHEDULER_NO_TASK;
   left = GNUNET_TIME_absolute_get_remaining (kx->timeout);
   if (left.rel_value == 0)
-  {    
+  {
+    GNUNET_STATISTICS_update (GSC_stats,
+                              gettext_noop ("# sessions terminated by timeout"),
+                              1, GNUNET_NO);
     GSC_SESSIONS_end (&kx->peer);
     kx->status = KX_STATE_DOWN;
     return;
   }
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending KEEPALIVE to `%s'\n",
+              GNUNET_i2s (&kx->peer));
+  GNUNET_STATISTICS_update (GSC_stats,
+                            gettext_noop ("# keepalive messages sent"), 1,
+                            GNUNET_NO);
   setup_fresh_ping (kx);
-  GDS_NEIGHBOURS_transmit (&kx->peer,
-                          &kx->ping.header,
-                          kx->set_key_retry_frequency);
+  GSC_NEIGHBOURS_transmit (&kx->peer, &kx->ping.header,
+                           kx->set_key_retry_frequency);
   retry =
       GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2),
                                 MIN_PING_FREQUENCY);
   kx->keep_alive_task =
-    GNUNET_SCHEDULER_add_delayed (retry, &send_keep_alive, kx);
+      GNUNET_SCHEDULER_add_delayed (retry, &send_keep_alive, kx);
+}
+
+
+/**
+ * We've seen a valid message from the other peer.
+ * Update the time when the session would time out
+ * and delay sending our keep alive message further.
+ *
+ * @param kx key exchange where we saw activity
+ */
+static void
+update_timeout (struct GSC_KeyExchangeInfo *kx)
+{
+  kx->timeout =
+      GNUNET_TIME_relative_to_absolute
+      (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
+  if (kx->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
+    GNUNET_SCHEDULER_cancel (kx->keep_alive_task);
+  kx->keep_alive_task =
+      GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide
+                                    (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
+                                     2), &send_keep_alive, kx);
+}
+
+
+/**
+ * Trigger rekeying event.
+ * 
+ * @param cls the 'struct GSC_KeyExchangeInfo'
+ * @param tc schedule context (unused)
+ */
+static void
+trigger_rekey (void *cls,
+              const struct GNUNET_SCHEDULER_TaskContext *tc)
+{
+  struct GSC_KeyExchangeInfo *kx = cls;
+  
+  kx->status = KX_STATE_REKEY;
+  kx->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY;
+  kx->retry_set_key_task =
+    GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
+                                 &set_key_retry_task, kx);
+}
+
+
+/**
+ * Schedule rekey operation.
+ *
+ * @param kx key exchange to schedule rekey for
+ */
+static void
+schedule_rekey (struct GSC_KeyExchangeInfo *kx)
+{
+  struct GNUNET_TIME_Relative rdelay;
 
+  if (GNUNET_SCHEDULER_NO_TASK != kx->retry_set_key_task)  
+    GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
+  rdelay = REKEY_FREQUENCY;
+  /* randomize rekey frequency by one minute to avoid synchronization */
+  rdelay.rel_value += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
+                                               60 * 1000);
+  kx->retry_set_key_task = GNUNET_SCHEDULER_add_delayed (REKEY_FREQUENCY,
+                                                        &trigger_rekey,
+                                                        kx);   
 }
 
 
@@ -962,19 +1154,17 @@ send_keep_alive (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
  * We received a PONG message.  Validate and update our status.
  *
  * @param kx key exchange context for the the PONG
- * @param m the encrypted PONG message itself
+ * @param msg the encrypted PONG message itself
  */
 void
-GSC_KX_handle_pong (struct GSC_KeyExchangeInfo *kx, const struct GNUNET_MessageHeader *msg)
+GSC_KX_handle_pong (struct GSC_KeyExchangeInfo *kx,
+                    const struct GNUNET_MessageHeader *msg)
 {
   const struct PongMessage *m;
   struct PongMessage t;
-  struct ConnectNotifyMessage *cnm;
+  struct EncryptedMessage *emsg;
   struct GNUNET_CRYPTO_AesInitializationVector iv;
-  char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
-  struct GNUNET_TRANSPORT_ATS_Information *mats;
   uint16_t msize;
-  size_t size;
 
   msize = ntohs (msg->size);
   if (msize != sizeof (struct PongMessage))
@@ -982,29 +1172,37 @@ GSC_KX_handle_pong (struct GSC_KeyExchangeInfo *kx, const struct GNUNET_MessageH
     GNUNET_break_op (0);
     return;
   }
-  GNUNET_STATISTICS_update (GSC_stats, gettext_noop ("# PONG messages received"),
-                           1, GNUNET_NO);
-
-  if ( (kx->status != KX_STATE_KEY_RECEIVED) &&
-       (kx->status != KX_STATE_UP) )
+  GNUNET_STATISTICS_update (GSC_stats,
+                            gettext_noop ("# PONG messages received"), 1,
+                            GNUNET_NO);
+  switch (kx->status)
   {
-    if (kx->status == KX_STATE_KEY_SENT)
-    {
-      GNUNET_free_non_null (n->pending_pong);
-      n->pending_pong = GNUNET_copy_message (msg);
-    }
+  case KX_STATE_DOWN:
+    return;
+  case KX_STATE_KEY_SENT:
+    GNUNET_free_non_null (kx->pong_received);
+    kx->pong_received = (struct PongMessage *) GNUNET_copy_message (msg);    
+    return;
+  case KX_STATE_KEY_RECEIVED:
+    break;
+  case KX_STATE_UP:
+    break;
+  case KX_STATE_REKEY:
+    break;
+  case KX_STATE_REKEY_SENT:
+    break;
+  default:
+    GNUNET_break (0);
     return;
   }
-  m = (const struct PongMessage*) msg;
-#if DEBUG_HANDSHAKE
+  m = (const struct PongMessage *) msg;
   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
               "Core service receives `%s' response from `%4s'.\n", "PONG",
               GNUNET_i2s (&kx->peer));
-#endif
   /* mark as garbage, just to be sure */
   memset (&t, 255, sizeof (t));
   derive_pong_iv (&iv, &kx->decrypt_key, m->iv_seed, kx->ping_challenge,
-                  &my_identity);
+                  &GSC_my_identity);
   if (GNUNET_OK !=
       do_decrypt (kx, &iv, &m->challenge, &t.challenge,
                   sizeof (struct PongMessage) - ((void *) &m->challenge -
@@ -1013,23 +1211,24 @@ GSC_KX_handle_pong (struct GSC_KeyExchangeInfo *kx, const struct GNUNET_MessageH
     GNUNET_break_op (0);
     return;
   }
-  GNUNET_STATISTICS_update (stats, gettext_noop ("# PONG messages decrypted"),
-                            1, GNUNET_NO);
+  GNUNET_STATISTICS_update (GSC_stats,
+                            gettext_noop ("# PONG messages decrypted"), 1,
+                            GNUNET_NO);
   if ((0 != memcmp (&t.target, &kx->peer, sizeof (struct GNUNET_PeerIdentity)))
       || (kx->ping_challenge != t.challenge))
   {
     /* PONG malformed */
-#if DEBUG_CORE
     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                 "Received malformed `%s' wanted sender `%4s' with challenge %u\n",
-                "PONG", GNUNET_i2s (&n->peer),
-                (unsigned int) n->ping_challenge);
+                "PONG", GNUNET_i2s (&kx->peer),
+                (unsigned int) kx->ping_challenge);
     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                 "Received malformed `%s' received from `%4s' with challenge %u\n",
                 "PONG", GNUNET_i2s (&t.target), (unsigned int) t.challenge);
-#endif
     return;
   }
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received PONG from `%s'\n",
+              GNUNET_i2s (&kx->peer));
   switch (kx->status)
   {
   case KX_STATE_DOWN:
@@ -1039,19 +1238,37 @@ GSC_KX_handle_pong (struct GSC_KeyExchangeInfo *kx, const struct GNUNET_MessageH
     GNUNET_break (0);           /* should be impossible */
     return;
   case KX_STATE_KEY_RECEIVED:
-    GNUNET_STATISTICS_update (stats,
+    GNUNET_STATISTICS_update (GSC_stats,
                               gettext_noop
-                              ("# Session keys confirmed via PONG"), 1,
+                              ("# session keys confirmed via PONG"), 1,
                               GNUNET_NO);
     kx->status = KX_STATE_UP;
-    GSC_SESSIONS_create (&kx->peer);
-    GNUNET_assert (kx->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK);
-    GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
-    kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
+    GSC_SESSIONS_create (&kx->peer, kx);
+    schedule_rekey (kx);
     GNUNET_assert (kx->keep_alive_task == GNUNET_SCHEDULER_NO_TASK);
+    if (kx->emsg_received != NULL)
+    {
+      emsg = kx->emsg_received;
+      kx->emsg_received = NULL;
+      GSC_KX_handle_encrypted_message (kx, &emsg->header, NULL,
+                                       0 /* FIXME: ATSI */ );
+      GNUNET_free (emsg);
+    }
+    update_timeout (kx);
+    break;
+  case KX_STATE_UP:
     update_timeout (kx);
     break;
-  case PEER_STATE_KEY_CONFIRMED:
+  case KX_STATE_REKEY:
+    update_timeout (kx);
+    break;
+  case KX_STATE_REKEY_SENT:
+    GNUNET_STATISTICS_update (GSC_stats,
+                              gettext_noop
+                              ("# rekey operations confirmed via PONG"), 1,
+                              GNUNET_NO);
+    kx->status = KX_STATE_UP;
+    schedule_rekey (kx);
     update_timeout (kx);
     break;
   default:
@@ -1069,58 +1286,80 @@ GSC_KX_handle_pong (struct GSC_KeyExchangeInfo *kx, const struct GNUNET_MessageH
 static void
 send_key (struct GSC_KeyExchangeInfo *kx)
 {
-  struct GNUNET_CRYPTO_AesInitializationVector iv;
-
-  GNUNET_assert (kx->retry_set_key_task == GNUNET_SCHEDULER_NO_TASK);
-  if (KX_STATE_UP == kx->status) 
-    return; /* nothing to do */
+  if (kx->retry_set_key_task != GNUNET_SCHEDULER_NO_TASK)
+  {
+     GNUNET_SCHEDULER_cancel (kx->retry_set_key_task);
+     kx->retry_set_key_task = GNUNET_SCHEDULER_NO_TASK;
+  }
+  if (KX_STATE_UP == kx->status)
+    return;                     /* nothing to do */
   if (kx->public_key == NULL)
   {
     /* lookup public key, then try again */
+    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                "Trying to obtain public key for `%s'\n",
+                GNUNET_i2s (&kx->peer));
     kx->pitr =
-      GNUNET_PEERINFO_iterate (peerinfo, &kx->peer,
-                              GNUNET_TIME_UNIT_FOREVER_REL /* timeout? */,
-                              &process_hello, kx);
+        GNUNET_PEERINFO_iterate (peerinfo, &kx->peer,
+                                 GNUNET_TIME_UNIT_FOREVER_REL /* timeout? */ ,
+                                 &process_hello, kx);
     return;
   }
 
   /* update status */
-  switch (n->status)
+  switch (kx->status)
   {
   case KX_STATE_DOWN:
-    n->status = PEER_STATE_KEY_SENT;    
+    kx->status = KX_STATE_KEY_SENT;
     /* setup SET KEY message */
-    setup_fresh_set_key (kx);
+    setup_fresh_setkey (kx);
     setup_fresh_ping (kx);
-    GNUNET_STATISTICS_update (stats,
-                             gettext_noop
-                             ("# SET_KEY and PING messages created"), 1,
-                             GNUNET_NO);
+    GNUNET_STATISTICS_update (GSC_stats,
+                              gettext_noop
+                              ("# SET_KEY and PING messages created"), 1,
+                              GNUNET_NO);
     break;
   case KX_STATE_KEY_SENT:
     break;
   case KX_STATE_KEY_RECEIVED:
     break;
-  case KX_STATE_KEY_CONFIRMED:
+  case KX_STATE_UP:
     GNUNET_break (0);
     return;
+  case KX_STATE_REKEY:
+    kx->status = KX_STATE_REKEY_SENT;
+    /* setup fresh SET KEY message */
+    setup_fresh_setkey (kx);
+    setup_fresh_ping (kx);
+    GNUNET_STATISTICS_update (GSC_stats,
+                              gettext_noop
+                              ("# SET_KEY and PING messages created"), 1,
+                              GNUNET_NO);
+    GNUNET_STATISTICS_update (GSC_stats,
+                              gettext_noop
+                              ("# REKEY operations performed"), 1,
+                              GNUNET_NO);
+    break;
+  case KX_STATE_REKEY_SENT:
+    break;
   default:
     GNUNET_break (0);
     return;
   }
 
   /* always update sender status in SET KEY message */
-  kx->skm.sender_status = htonl ((int32_t) kx->status);
-
-  GDS_NEIGHBOURS_transmit (&kx->peer,
-                          &kx->skm.header,
-                          kx->set_key_retry_frequency);
-  GDS_NEIGHBOURS_transmit (&kx->peer,
-                          &kx->ping.header,
-                          kx->set_key_retry_frequency);
+  /* Not sending rekey sent state to be compatible with GNUnet 0.9.2 */
+  kx->skm.sender_status = htonl ((int32_t) ((kx->status == KX_STATE_REKEY_SENT) ? 
+                                           KX_STATE_KEY_RECEIVED : kx->status));  
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending SET_KEY and PING to `%s'\n",
+              GNUNET_i2s (&kx->peer));
+  GSC_NEIGHBOURS_transmit (&kx->peer, &kx->skm.header,
+                           kx->set_key_retry_frequency);
+  GSC_NEIGHBOURS_transmit (&kx->peer, &kx->ping.header,
+                           kx->set_key_retry_frequency);
   kx->retry_set_key_task =
-    GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
-                                 &set_key_retry_task, kx);
+      GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency,
+                                    &set_key_retry_task, kx);
 }
 
 
@@ -1128,38 +1367,27 @@ send_key (struct GSC_KeyExchangeInfo *kx)
  * Encrypt and transmit a message with the given payload.
  *
  * @param kx key exchange context
- * @param bw_in bandwidth limit to transmit to the other peer;
- *              the other peer shall not send us more than the
- *              given rate
  * @param payload payload of the message
  * @param payload_size number of bytes in 'payload'
  */
 void
 GSC_KX_encrypt_and_transmit (struct GSC_KeyExchangeInfo *kx,
-                            struct GNUNET_BANDWIDTH_Value32NBO bw_in,
-                            const void *payload,
-                            size_t payload_size)
+                             const void *payload, size_t payload_size)
 {
   size_t used = payload_size + sizeof (struct EncryptedMessage);
-  char pbuf[used]; /* plaintext */
-  char cbuf[used]; /* ciphertext */
+  char pbuf[used];              /* plaintext */
+  char cbuf[used];              /* ciphertext */
   struct EncryptedMessage *em;  /* encrypted message */
   struct EncryptedMessage *ph;  /* plaintext header */
   struct GNUNET_CRYPTO_AesInitializationVector iv;
   struct GNUNET_CRYPTO_AuthKey auth_key;
 
-#if DEBUG_CORE_QUOTA
-  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
-              "Sending %u b/s as new limit to peer `%4s'\n",
-              (unsigned int) ntohl (bw_in.value__),
-             GNUNET_i2s (&kx->peer));
-#endif
-  ph = (struct EncryptedMessage*) pbuf;
+  ph = (struct EncryptedMessage *) pbuf;
   ph->iv_seed =
       htonl (GNUNET_CRYPTO_random_u32
              (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
   ph->sequence_number = htonl (++kx->last_sequence_number_sent);
-  ph->inbound_bw_limit = bw_in;
+  ph->reserved = GNUNET_BANDWIDTH_VALUE_MAX;
   ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
   memcpy (&ph[1], payload, payload_size);
 
@@ -1169,62 +1397,68 @@ GSC_KX_encrypt_and_transmit (struct GSC_KeyExchangeInfo *kx,
   em->iv_seed = ph->iv_seed;
   derive_iv (&iv, &kx->encrypt_key, ph->iv_seed, &kx->peer);
   GNUNET_assert (GNUNET_OK ==
-                 do_encrypt (kx, &iv, &ph->sequence_number, &em->sequence_number,
+                 do_encrypt (kx, &iv, &ph->sequence_number,
+                             &em->sequence_number,
                              used - ENCRYPTED_HEADER_SIZE));
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Encrypted %u bytes for %s\n",
+              used - ENCRYPTED_HEADER_SIZE, GNUNET_i2s (&kx->peer));
   derive_auth_key (&auth_key, &kx->encrypt_key, ph->iv_seed,
                    kx->encrypt_key_created);
   GNUNET_CRYPTO_hmac (&auth_key, &em->sequence_number,
                       used - ENCRYPTED_HEADER_SIZE, &em->hmac);
-  GDS_NEIGHBOURS_transmit (&kx->peer,
-                          &em->header,
-                          GNUNET_TIME_UNIT_FOREVER_REL);
-}                 
+  GSC_NEIGHBOURS_transmit (&kx->peer, &em->header,
+                           GNUNET_TIME_UNIT_FOREVER_REL);
+}
 
 
 /**
- * We've seen a valid message from the other peer.
- * Update the time when the session would time out
- * and delay sending our keep alive message further.
- *
- * @param kx key exchange where we saw activity
+ * Closure for 'deliver_message'
  */
-static void
-update_timeout (struct GSC_KeyExchangeInfo *kx)
+struct DeliverMessageContext
 {
-  kx->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
-  if (kx->keep_alive_task != GNUNET_SCHEDULER_NO_TASK)
-    GNUNET_SCHEDULER_cancel (n->keep_alive_task);
-  kx->keep_alive_task =
-    GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_divide
-                                 (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
-                                  2), &send_keep_alive, kx);
-}
+
+  /**
+   * Performance information for the connection.
+   */
+  const struct GNUNET_ATS_Information *atsi;
+
+  /**
+   * Sender of the message.
+   */
+  const struct GNUNET_PeerIdentity *peer;
+
+  /**
+   * Number of entries in 'atsi' array.
+   */
+  uint32_t atsi_count;
+};
 
 
 /**
  * We received an encrypted message.  Decrypt, validate and
  * pass on to the appropriate clients.
  *
- * @param n target of the message
- * @param m encrypted message
+ * @param kx key exchange context for encrypting the message
+ * @param msg encrypted message
  * @param atsi performance data
  * @param atsi_count number of entries in ats (excluding 0-termination)
  */
 void
-GSC_KX_handle_encrypted_message (struct GSC_KeyExchangeInfo *n, 
-                                const struct GNUNET_MessageHeader *msg,
-                                const struct GNUNET_TRANSPORT_ATS_Information *atsi,
-                                uint32_t atsi_count)
+GSC_KX_handle_encrypted_message (struct GSC_KeyExchangeInfo *kx,
+                                 const struct GNUNET_MessageHeader *msg,
+                                 const struct GNUNET_ATS_Information *atsi,
+                                 uint32_t atsi_count)
 {
   const struct EncryptedMessage *m;
-  char buf[size];
   struct EncryptedMessage *pt;  /* plaintext */
   GNUNET_HashCode ph;
   uint32_t snum;
   struct GNUNET_TIME_Absolute t;
   struct GNUNET_CRYPTO_AesInitializationVector iv;
   struct GNUNET_CRYPTO_AuthKey auth_key;
+  struct DeliverMessageContext dmc;
   uint16_t size = ntohs (msg->size);
+  char buf[size];
 
   if (size <
       sizeof (struct EncryptedMessage) + sizeof (struct GNUNET_MessageHeader))
@@ -1232,14 +1466,21 @@ GSC_KX_handle_encrypted_message (struct GSC_KeyExchangeInfo *n,
     GNUNET_break_op (0);
     return;
   }
-  m = (const struct EncryptedMessage*) msg;
-  if ( (kx->status != KX_STATE_KEY_RECEIVED) &&
-       (kx->status != KX_STATE_UP) )
+  m = (const struct EncryptedMessage *) msg;
+  if ((kx->status != KX_STATE_KEY_RECEIVED) && (kx->status != KX_STATE_UP) &&
+      (kx->status != KX_STATE_REKEY_SENT) )
   {
-    GNUNET_STATISTICS_update (stats,
-                             gettext_noop
-                             ("# failed to decrypt message (no session key)"),
-                             1, GNUNET_NO);
+    GNUNET_STATISTICS_update (GSC_stats,
+                              gettext_noop
+                              ("# failed to decrypt message (no session key)"),
+                              1, GNUNET_NO);
+    return;
+  }
+  if (kx->status == KX_STATE_KEY_RECEIVED)
+  {
+    /* defer */
+    GNUNET_free_non_null (kx->ping_received);
+    kx->emsg_received = (struct EncryptedMessage *) GNUNET_copy_message (msg);
     return;
   }
   /* validate hash */
@@ -1259,6 +1500,8 @@ GSC_KX_handle_encrypted_message (struct GSC_KeyExchangeInfo *n,
       do_decrypt (kx, &iv, &m->sequence_number, &buf[ENCRYPTED_HEADER_SIZE],
                   size - ENCRYPTED_HEADER_SIZE))
     return;
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Decrypted %u bytes from %s\n",
+              size - ENCRYPTED_HEADER_SIZE, GNUNET_i2s (&kx->peer));
   pt = (struct EncryptedMessage *) buf;
 
   /* validate sequence number */
@@ -1293,7 +1536,7 @@ GSC_KX_handle_encrypted_message (struct GSC_KeyExchangeInfo *n,
     {
       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                   "Received duplicate message, ignoring.\n");
-      GNUNET_STATISTICS_update (stats,
+      GNUNET_STATISTICS_update (GSC_stats,
                                 gettext_noop ("# bytes dropped (duplicates)"),
                                 size, GNUNET_NO);
       /* duplicate, ignore */
@@ -1320,7 +1563,7 @@ GSC_KX_handle_encrypted_message (struct GSC_KeyExchangeInfo *n,
     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                 _("Message received far too old (%llu ms). Content ignored.\n"),
                 GNUNET_TIME_absolute_get_duration (t).rel_value);
-    GNUNET_STATISTICS_update (stats,
+    GNUNET_STATISTICS_update (GSC_stats,
                               gettext_noop
                               ("# bytes dropped (ancient message)"), size,
                               GNUNET_NO);
@@ -1329,24 +1572,25 @@ GSC_KX_handle_encrypted_message (struct GSC_KeyExchangeInfo *n,
 
   /* process decrypted message(s) */
   update_timeout (kx);
-  GSC_SESSIONS_update (&kx->peer,
-                      pt->inbound_bw_limit,
-                      atsi, atsi_count); // FIXME: does 'SESSIONS' need atsi!?
-  GNUNET_STATISTICS_update (stats,
+  GNUNET_STATISTICS_update (GSC_stats,
                             gettext_noop ("# bytes of payload decrypted"),
                             size - sizeof (struct EncryptedMessage), GNUNET_NO);
+  dmc.atsi = atsi;
+  dmc.atsi_count = atsi_count;
+  dmc.peer = &kx->peer;
   if (GNUNET_OK !=
-      GNUNET_SERVER_mst_receive (mst, kx, &buf[sizeof (struct EncryptedMessage)],
+      GNUNET_SERVER_mst_receive (mst, &dmc,
+                                 &buf[sizeof (struct EncryptedMessage)],
                                  size - sizeof (struct EncryptedMessage),
                                  GNUNET_YES, GNUNET_NO))
     GNUNET_break_op (0);
 }
 
 
-
-
 /**
  * Deliver P2P message to interested clients.
+ * Invokes send twice, once for clients that want the full message, and once
+ * for clients that only want the header
  *
  * @param cls always NULL
  * @param client who sent us the message (struct GSC_KeyExchangeInfo)
@@ -1355,38 +1599,42 @@ GSC_KX_handle_encrypted_message (struct GSC_KeyExchangeInfo *n,
 static void
 deliver_message (void *cls, void *client, const struct GNUNET_MessageHeader *m)
 {
-  struct GSC_KeyExchangeInfo *kx = client;
-
-  // FIXME (need to check stuff, need ATSI, etc.)
-  // FIXME: does clients work properly if never called with option 'NOTHING'!?
-  GSC_CLIENTS_deliver_message (&kx->peer,
-                              NULL, 0, // kx->atsi...
-                              m,
-                              ntohs (m->size),
-                              GNUNET_CORE_OPTION_SEND_FULL_INBOUND);
-  GSC_CLIENTS_deliver_message (&kx->peer,
-                              NULL, 0, // kx->atsi...
-                              m,
-                              sizeof (struct GNUNET_MessageHeader),
-                              GNUNET_CORE_OPTION_SEND_HDR_INBOUND);
+  struct DeliverMessageContext *dmc = client;
+
+  switch (ntohs (m->type))
+  {
+  case GNUNET_MESSAGE_TYPE_CORE_BINARY_TYPE_MAP:
+  case GNUNET_MESSAGE_TYPE_CORE_COMPRESSED_TYPE_MAP:
+    GSC_SESSIONS_set_typemap (dmc->peer, m);
+    return;
+  default:
+    GSC_CLIENTS_deliver_message (dmc->peer, dmc->atsi, dmc->atsi_count, m,
+                                 ntohs (m->size),
+                                 GNUNET_CORE_OPTION_SEND_FULL_INBOUND);
+    GSC_CLIENTS_deliver_message (dmc->peer, dmc->atsi, dmc->atsi_count, m,
+                                 sizeof (struct GNUNET_MessageHeader),
+                                 GNUNET_CORE_OPTION_SEND_HDR_INBOUND);
+  }
 }
 
+
 /**
  * Initialize KX subsystem.
  *
  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
  */
-int 
+int
 GSC_KX_init ()
 {
   char *keyfile;
 
   if (GNUNET_OK !=
       GNUNET_CONFIGURATION_get_value_filename (GSC_cfg, "GNUNETD", "HOSTKEY",
-                                              &keyfile))
+                                               &keyfile))
   {
     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
-                _("Core service is lacking HOSTKEY configuration setting.  Exiting.\n"));
+                _
+                ("Core service is lacking HOSTKEY configuration setting.  Exiting.\n"));
     return GNUNET_SYSERR;
   }
   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
@@ -1399,8 +1647,8 @@ GSC_KX_init ()
   }
   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
-                      &my_identity.hashPubKey);
-  peerinfo = GNUNET_PEERINFO_connect (cfg);
+                      &GSC_my_identity.hashPubKey);
+  peerinfo = GNUNET_PEERINFO_connect (GSC_cfg);
   if (NULL == peerinfo)
   {
     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
@@ -1417,7 +1665,7 @@ GSC_KX_init ()
 /**
  * Shutdown KX subsystem.
  */
-void 
+void
 GSC_KX_done ()
 {
   if (my_private_key != NULL)