Merge branch 'master' of ssh://gnunet.org/gnunet
[oweals/gnunet.git] / src / identity-provider / gnunet-service-identity-provider.c
index 85471e6574a402cb26c455b78ad9272a2581fa03..17c2883682e0e1627ecba4474eb31dd83add27e0 100644 (file)
@@ -1,6 +1,6 @@
 /*
    This file is part of GNUnet.
-   Copyright (C) 2012-2015 Christian Grothoff (and other contributing authors)
+   Copyright (C) 2012-2015 GNUnet e.V.
 
    GNUnet is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published
@@ -19,7 +19,7 @@
    */
 /**
  * @author Martin Schanzenbach
- * @file src/identity/gnunet-service-identity-provider.c
+ * @file src/identity-provider/gnunet-service-identity-provider.c
  * @brief Identity Token Service
  *
  */
 #include "gnunet_namestore_service.h"
 #include "gnunet_statistics_service.h"
 #include "gnunet_gns_service.h"
-#include <jansson.h>
 #include "gnunet_signatures.h"
 #include "identity_provider.h"
 #include "identity_token.h"
+#include <inttypes.h>
 
 /**
  * First pass state
  */
 #define MIN_WAIT_TIME GNUNET_TIME_UNIT_MINUTES
 
+/**
+ * Standard token expiration time
+ */
+#define DEFAULT_TOKEN_EXPIRATION_INTERVAL GNUNET_TIME_UNIT_HOURS
+
 /**
  * Service state (to detect initial update pass)
  */
@@ -72,6 +77,11 @@ static struct EgoEntry *ego_tail;
  */
 static struct GNUNET_IDENTITY_Handle *identity_handle;
 
+/**
+ * Token expiration interval
+ */
+static struct GNUNET_TIME_Relative token_expiration_interval;
+
 /**
  * Namestore handle
  */
@@ -95,13 +105,12 @@ static struct GNUNET_NAMESTORE_ZoneIterator *ns_it;
 /**
  * Timeout task
  */
-static struct GNUNET_SCHEDULER_Task * timeout_task;
-
+static struct GNUNET_SCHEDULER_Task *timeout_task;
 
 /**
  * Update task
  */
-static struct GNUNET_SCHEDULER_Task * update_task;
+static struct GNUNET_SCHEDULER_Task *update_task;
 
 /**
  * Timeout for next update pass
@@ -140,9 +149,10 @@ static struct GNUNET_CRYPTO_EcdhePrivateKey ecdhe_privkey;
 static struct GNUNET_STATISTICS_Handle *stats;
 
 /**
- * Notification context, simplifies client broadcasts.
+ * Our configuration.
  */
-static struct GNUNET_SERVER_NotificationContext *nc;
+static const struct GNUNET_CONFIGURATION_Handle *cfg;
+
 
 struct ExchangeHandle
 {
@@ -150,7 +160,7 @@ struct ExchangeHandle
   /**
    * Client connection
    */
-  struct GNUNET_SERVER_Client *client;
+  struct GNUNET_SERVICE_Client *client;
 
   /**
    * Ticket
@@ -166,7 +176,7 @@ struct ExchangeHandle
    * LookupRequest
    */
   struct GNUNET_GNS_LookupRequest *lookup_request;
-  
+
   /**
    * Audience Key
    */
@@ -176,6 +186,11 @@ struct ExchangeHandle
    * Label to return
    */
   char *label;
+
+  /**
+   * request id
+   */
+  uint32_t r_id;
 };
 
 struct IssueHandle
@@ -184,7 +199,7 @@ struct IssueHandle
   /**
    * Client connection
    */
-  struct GNUNET_SERVER_Client *client;
+  struct GNUNET_SERVICE_Client *client;
 
   /**
    * Issuer Key
@@ -240,6 +255,16 @@ struct IssueHandle
    * QueueEntry
    */
   struct GNUNET_NAMESTORE_QueueEntry *ns_qe;
+
+  /**
+   * The label the token is stored under
+   */
+  char *label;
+
+  /**
+   * request id
+   */
+  uint32_t r_id;
 };
 
 /**
@@ -275,18 +300,12 @@ struct EgoEntry
 };
 
 /**
- * Our configuration.
+ * Continuation for token store call
+ *
+ * @param cls NULL
+ * @param success error code
+ * @param emsg error message
  */
-  static const struct GNUNET_CONFIGURATION_Handle *cfg;
-
-
-  /**
-   * Continuation for token store call
-   *
-   * @param cls NULL
-   * @param success error code
-   * @param emsg error message
-   */
 static void
 store_token_cont (void *cls,
                   int32_t success,
@@ -309,16 +328,13 @@ store_token_cont (void *cls,
  * removes deleted attributes and expiration times.
  *
  * @param cls the ego entry
- * @param tc task context
  */
 static void
-handle_token_update (void *cls,
-                     const struct GNUNET_SCHEDULER_TaskContext *tc)
+handle_token_update (void *cls)
 {
   char *token_metadata;
   char *write_ptr;
   char *enc_token_str;
-  const char *key;
   const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv_key;
   struct GNUNET_CRYPTO_EcdsaPublicKey pub_key;
   struct GNUNET_CRYPTO_EcdhePrivateKey *new_ecdhe_privkey;
@@ -333,11 +349,8 @@ handle_token_update (void *cls,
   struct GNUNET_TIME_Absolute new_iat;
   struct GNUNET_TIME_Absolute new_nbf;
   struct IdentityToken *new_token;
-  json_t *payload_json;
-  json_t *value;
-  json_t *cur_value;
-  json_t *token_nbf_json;
-  json_t *token_exp_json;
+  struct TokenAttr *cur_value;
+  struct TokenAttr *attr;
   size_t token_metadata_len;
 
   priv_key = GNUNET_IDENTITY_ego_get_private_key (ego_entry->ego);
@@ -353,12 +366,19 @@ handle_token_update (void *cls,
   //but this service will reissue new tokens that can be retrieved from GNS
   //automatically.
 
-  payload_json = token->payload;
-
-  token_exp_json = json_object_get (payload_json, "exp");
-  token_nbf_json = json_object_get (payload_json, "nbf");
-  token_exp.abs_value_us = json_integer_value(token_exp_json);
-  token_nbf.abs_value_us = json_integer_value(token_nbf_json);
+  for (attr = token->attr_head; NULL != attr; attr = attr->next)
+  {
+    if (0 == strcmp (attr->name, "exp"))
+    {
+      GNUNET_assert (1 == sscanf (attr->val_head->value,
+              "%"SCNu64,
+              &token_exp.abs_value_us));
+    } else if (0 == strcmp (attr->name, "nbf")) {
+      GNUNET_assert (1 == sscanf (attr->val_head->value,
+              "%"SCNu64,
+              &token_nbf.abs_value_us));
+    }
+  }
   token_rel_exp = GNUNET_TIME_absolute_get_difference (token_nbf, token_exp);
 
   token_ttl = GNUNET_TIME_absolute_get_remaining (token_exp);
@@ -369,7 +389,6 @@ handle_token_update (void *cls,
     {
       min_rel_exp = token_ttl;
     }
-    json_decref (payload_json);
     GNUNET_free (token);
     token = NULL;
     GNUNET_free (label);
@@ -386,41 +405,46 @@ handle_token_update (void *cls,
   new_exp = GNUNET_TIME_relative_to_absolute (token_rel_exp);
   new_nbf = GNUNET_TIME_absolute_get ();
   new_iat = new_nbf;
-
-  json_object_foreach(payload_json, key, value) {
-    if (0 == strcmp (key, "exp"))
+  for (attr = token->attr_head; NULL != attr; attr = attr->next)
+  {
+    if (0 == strcmp (attr->name, "exp"))
     {
-      token_add_json (new_token, key, json_integer (new_exp.abs_value_us));
+      token_add_attr_int (new_token, attr->name, new_exp.abs_value_us);
     }
-    else if (0 == strcmp (key, "nbf"))
+    else if (0 == strcmp (attr->name, "nbf"))
     {
-      token_add_json (new_token, key, json_integer (new_nbf.abs_value_us));
+      token_add_attr_int (new_token, attr->name, new_nbf.abs_value_us);
     }
-    else if (0 == strcmp (key, "iat"))
+    else if (0 == strcmp (attr->name, "iat"))
     {
-      token_add_json (new_token, key, json_integer (new_iat.abs_value_us));
+      token_add_attr_int (new_token, attr->name, new_iat.abs_value_us);
     }
-    else if ((0 == strcmp (key, "iss"))
-             || (0 == strcmp (key, "aud")))
+    else if ((0 == strcmp (attr->name, "iss"))
+             || (0 == strcmp (attr->name, "aud")))
     {
       //Omit
     }
-    else if ((0 == strcmp (key, "sub"))
-             || (0 == strcmp (key, "rnl")))
+    else if (0 == strcmp (attr->name, "sub"))
     {
-      token_add_json (new_token, key, value);
+      token_add_attr (new_token,
+                      attr->name,
+                      attr->val_head->value);
     }
-    else {
-      GNUNET_CRYPTO_hash (key,
-                          strlen (key),
+    else
+    {
+      GNUNET_CRYPTO_hash (attr->name,
+                          strlen (attr->name),
                           &key_hash);
       //Check if attr still exists. omit of not
-      if (GNUNET_NO != GNUNET_CONTAINER_multihashmap_contains (ego_entry->attr_map,
-                                                               &key_hash))
+      if (GNUNET_NO !=
+          GNUNET_CONTAINER_multihashmap_contains (ego_entry->attr_map,
+                                                  &key_hash))
       {
         cur_value = GNUNET_CONTAINER_multihashmap_get (ego_entry->attr_map,
                                                        &key_hash);
-        token_add_json (new_token, key, cur_value);
+        GNUNET_CONTAINER_DLL_insert (new_token->attr_head,
+                                     new_token->attr_tail,
+                                     cur_value);
       }
     }
   }
@@ -431,8 +455,6 @@ handle_token_update (void *cls,
                                   &new_ecdhe_privkey,
                                   &enc_token_str));
 
-  json_decref (payload_json);
-
   token_record[0].data = enc_token_str;
   token_record[0].data_size = strlen (enc_token_str) + 1;
   token_record[0].expiration_time = rd_exp; //Old expiration time
@@ -445,11 +467,11 @@ handle_token_update (void *cls,
     + strlen (scopes) + 1; //With 0-Terminator
   token_metadata = GNUNET_malloc (token_metadata_len);
   write_ptr = token_metadata;
-  memcpy (token_metadata, new_ecdhe_privkey, sizeof (struct GNUNET_CRYPTO_EcdhePrivateKey));
+  GNUNET_memcpy (token_metadata, new_ecdhe_privkey, sizeof (struct GNUNET_CRYPTO_EcdhePrivateKey));
   write_ptr += sizeof (struct GNUNET_CRYPTO_EcdhePrivateKey);
-  memcpy (write_ptr, &token->aud_key, sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey));
+  GNUNET_memcpy (write_ptr, &token->aud_key, sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey));
   write_ptr += sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey);
-  memcpy (write_ptr, scopes, strlen (scopes) + 1); //with 0-Terminator;
+  GNUNET_memcpy (write_ptr, scopes, strlen (scopes) + 1); //with 0-Terminator;
 
   token_record[1].data = token_metadata;
   token_record[1].data_size = token_metadata_len;
@@ -464,7 +486,6 @@ handle_token_update (void *cls,
                                           token_record,
                                           &store_token_cont,
                                           ego_entry);
-  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, ">>> Updating Token w/ %s\n", new_token);
   token_destroy (new_token);
   token_destroy (token);
   GNUNET_free (new_ecdhe_privkey);
@@ -476,9 +497,10 @@ handle_token_update (void *cls,
   scopes = NULL;
 }
 
+
 static void
-update_identities(void *cls,
-                  const struct GNUNET_SCHEDULER_TaskContext *tc);
+update_identities(void *cls);
+
 
 /**
  *
@@ -487,21 +509,68 @@ update_identities(void *cls,
  * @param cls NULL
  * @param key the key
  * @param value the json_t attribute value
- * @return GNUNET_YES
+ * @return #GNUNET_YES
  */
 static int
 clear_ego_attrs (void *cls,
                  const struct GNUNET_HashCode *key,
                  void *value)
 {
-  json_t *attr_value = value;
-
-  json_decref (attr_value);
+  struct TokenAttr *attr = value;
+  struct TokenAttrValue *val;
+  struct TokenAttrValue *tmp_val;
+  for (val = attr->val_head; NULL != val;)
+  {
+    tmp_val = val->next;
+    GNUNET_CONTAINER_DLL_remove (attr->val_head,
+                                 attr->val_tail,
+                                 val);
+    GNUNET_free (val->value);
+    GNUNET_free (val);
+    val = tmp_val;
+  }
+  GNUNET_free (attr->name);
+  GNUNET_free (attr);
 
   return GNUNET_YES;
 }
 
 
+static void
+token_collect_error_cb (void *cls)
+{
+  struct EgoEntry *ego_entry = cls;
+
+  GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
+              ">>> Updating Ego failed!\n");
+  //Clear attribute map for ego
+  GNUNET_CONTAINER_multihashmap_iterate (ego_entry->attr_map,
+                                         &clear_ego_attrs,
+                                         ego_entry);
+  GNUNET_CONTAINER_multihashmap_clear (ego_entry->attr_map);
+  update_task = GNUNET_SCHEDULER_add_now (&update_identities,
+                                          ego_entry->next);
+
+}
+
+
+static void
+token_collect_finished_cb (void *cls)
+{
+  struct EgoEntry *ego_entry = cls;
+
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+              ">>> Updating Ego finished\n");
+  //Clear attribute map for ego
+  GNUNET_CONTAINER_multihashmap_iterate (ego_entry->attr_map,
+                                         &clear_ego_attrs,
+                                         ego_entry);
+  GNUNET_CONTAINER_multihashmap_clear (ego_entry->attr_map);
+  update_task = GNUNET_SCHEDULER_add_now (&update_identities,
+                                          ego_entry->next);
+}
+
+
 /**
  *
  * Update all ID_TOKEN records for an identity and store them
@@ -511,7 +580,6 @@ clear_ego_attrs (void *cls,
  * @param lbl the name of the record
  * @param rd_count number of records
  * @param rd record data
- *
  */
 static void
 token_collect (void *cls,
@@ -524,20 +592,7 @@ token_collect (void *cls,
   const struct GNUNET_GNSRECORD_Data *token_record;
   const struct GNUNET_GNSRECORD_Data *token_metadata_record;
   struct GNUNET_CRYPTO_EcdsaPublicKey *aud_key;
-
-  if (NULL == lbl)
-  {
-    //Done
-    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
-                ">>> Updating Ego finished\n");
-    //Clear attribute map for ego
-    GNUNET_CONTAINER_multihashmap_iterate (ego_entry->attr_map,
-                                           &clear_ego_attrs,
-                                           ego_entry);
-    GNUNET_CONTAINER_multihashmap_clear (ego_entry->attr_map);
-    GNUNET_SCHEDULER_add_now (&update_identities, ego_entry->next);
-    return;
-  }
+  struct GNUNET_CRYPTO_EcdhePrivateKey *priv_key;
 
   //There should be only a single record for a token under a label
   if (2 != rd_count)
@@ -550,16 +605,27 @@ token_collect (void *cls,
   {
     token_metadata_record = &rd[0];
     token_record = &rd[1];
-  } else {
+  }
+  else
+  {
     token_record = &rd[0];
     token_metadata_record = &rd[1];
   }
-  GNUNET_assert (token_metadata_record->record_type == GNUNET_GNSRECORD_TYPE_ID_TOKEN_METADATA);
-  GNUNET_assert (token_record->record_type == GNUNET_GNSRECORD_TYPE_ID_TOKEN);
+  if (token_metadata_record->record_type != GNUNET_GNSRECORD_TYPE_ID_TOKEN_METADATA)
+  {
+    GNUNET_NAMESTORE_zone_iterator_next (ns_it);
+    return;
+  }
+  if (token_record->record_type == GNUNET_GNSRECORD_TYPE_ID_TOKEN)
+  {
+    GNUNET_NAMESTORE_zone_iterator_next (ns_it);
+    return;
+  }
 
   //Get metadata and decrypt token
-  ecdhe_privkey = *((struct GNUNET_CRYPTO_EcdhePrivateKey *)token_metadata_record->data);
-  aud_key = (struct GNUNET_CRYPTO_EcdsaPublicKey *)&ecdhe_privkey+sizeof(struct GNUNET_CRYPTO_EcdhePrivateKey);
+  priv_key = (struct GNUNET_CRYPTO_EcdhePrivateKey *)token_metadata_record->data;
+  ecdhe_privkey = *priv_key;
+  aud_key = (struct GNUNET_CRYPTO_EcdsaPublicKey *)&priv_key[1];
   scopes = GNUNET_strdup ((char*) aud_key+sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey));
 
   token_parse2 (token_record->data,
@@ -567,13 +633,37 @@ token_collect (void *cls,
                 aud_key,
                 &token);
 
-  //token = GNUNET_GNSRECORD_value_to_string (rd->record_type,
-  //                                          rd->data,
-  //                                          rd->data_size);
-  label = GNUNET_strdup (lbl); 
+  label = GNUNET_strdup (lbl);
   rd_exp = token_record->expiration_time;
 
-  GNUNET_SCHEDULER_add_now (&handle_token_update, ego_entry);
+  GNUNET_SCHEDULER_add_now (&handle_token_update,
+                            ego_entry);
+}
+
+
+static void
+attribute_collect_error_cb (void *cls)
+{
+  struct EgoEntry *ego_entry = cls;
+
+  GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
+              ">>> Updating Attributes failed!\n");
+  ego_entry->attributes_dirty = GNUNET_NO;
+  update_task = GNUNET_SCHEDULER_add_now (&update_identities,
+                                          ego_entry);
+}
+
+
+static void
+attribute_collect_finished_cb (void *cls)
+{
+  struct EgoEntry *ego_entry = cls;
+
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+              ">>> Updating Attributes finished\n");
+  ego_entry->attributes_dirty = GNUNET_NO;
+  update_task = GNUNET_SCHEDULER_add_now (&update_identities,
+                                          ego_entry);
 }
 
 
@@ -596,21 +686,12 @@ attribute_collect (void *cls,
                    const struct GNUNET_GNSRECORD_Data *rd)
 {
   struct EgoEntry *ego_entry = cls;
-  json_t *attr_value;
   struct GNUNET_HashCode key;
-  char* attr;
+  struct TokenAttr *attr;
+  struct TokenAttrValue *val;
+  char *val_str;
   int i;
 
-  if (NULL == lbl)
-  {
-    //Done
-    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
-                ">>> Updating Attributes finished\n");
-    ego_entry->attributes_dirty = GNUNET_NO;
-    GNUNET_SCHEDULER_add_now (&update_identities, ego_entry);
-    return;
-  }
-
   if (0 == rd_count)
   {
     GNUNET_NAMESTORE_zone_iterator_next (ns_it);
@@ -623,40 +704,48 @@ attribute_collect (void *cls,
   {
     if (rd->record_type == GNUNET_GNSRECORD_TYPE_ID_ATTR)
     {
-      attr = GNUNET_GNSRECORD_value_to_string (rd->record_type,
-                                               rd->data,
-                                               rd->data_size);
-      attr_value = json_string (attr);
-      GNUNET_CONTAINER_multihashmap_put (ego_entry->attr_map,
-                                         &key,
-                                         attr_value,
-                                         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
-      GNUNET_free (attr);
+      val_str = GNUNET_GNSRECORD_value_to_string (rd->record_type,
+                                                  rd->data,
+                                                  rd->data_size);
+      attr = GNUNET_malloc (sizeof (struct TokenAttr));
+      attr->name = GNUNET_strdup (lbl);
+      val = GNUNET_malloc (sizeof (struct TokenAttrValue));
+      val->value = val_str;
+      GNUNET_CONTAINER_DLL_insert (attr->val_head,
+                                   attr->val_tail,
+                                   val);
+      GNUNET_assert (GNUNET_OK ==
+                     GNUNET_CONTAINER_multihashmap_put (ego_entry->attr_map,
+                                                        &key,
+                                                        attr,
+                                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
     }
 
     GNUNET_NAMESTORE_zone_iterator_next (ns_it);
     return;
   }
 
-  attr_value = json_array();
+  attr = GNUNET_malloc (sizeof (struct TokenAttr));
+  attr->name = GNUNET_strdup (lbl);
   for (i = 0; i < rd_count; i++)
   {
     if (rd[i].record_type == GNUNET_GNSRECORD_TYPE_ID_ATTR)
     {
-      attr = GNUNET_GNSRECORD_value_to_string (rd[i].record_type,
-                                               rd[i].data,
-                                               rd[i].data_size);
-      json_array_append_new (attr_value, json_string (attr));
-      GNUNET_free (attr);
+      val_str = GNUNET_GNSRECORD_value_to_string (rd[i].record_type,
+                                                  rd[i].data,
+                                                  rd[i].data_size);
+      val = GNUNET_malloc (sizeof (struct TokenAttrValue));
+      val->value = val_str;
+      GNUNET_CONTAINER_DLL_insert (attr->val_head,
+                                   attr->val_tail,
+                                   val);
     }
-
   }
-  GNUNET_CONTAINER_multihashmap_put (ego_entry->attr_map,
-                                     &key,
-                                     attr_value,
-                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
+  GNUNET_assert (GNUNET_OK == GNUNET_CONTAINER_multihashmap_put (ego_entry->attr_map,
+                                                                 &key,
+                                                                 attr,
+                                                                 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
   GNUNET_NAMESTORE_zone_iterator_next (ns_it);
-  return;
 }
 
 /**
@@ -665,24 +754,23 @@ attribute_collect (void *cls,
  * dirty, first update the attributes.
  *
  * @param cls the ego to update
- * param tc task context
- *
  */
 static void
-update_identities(void *cls,
-                  const struct GNUNET_SCHEDULER_TaskContext *tc)
+update_identities(void *cls)
 {
   struct EgoEntry *next_ego = cls;
   const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv_key;
+
+  update_task = NULL;
   if (NULL == next_ego)
   {
     if (min_rel_exp.rel_value_us < MIN_WAIT_TIME.rel_value_us)
       min_rel_exp = MIN_WAIT_TIME;
     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
-                ">>> Finished. Rescheduling in %d\n",
+                ">>> Finished. Rescheduling in %"SCNu64"\n",
                 min_rel_exp.rel_value_us);
     ns_it = NULL;
-    //finished -> TODO reschedule
+    //finished -> reschedule
     update_task = GNUNET_SCHEDULER_add_delayed (min_rel_exp,
                                                 &update_identities,
                                                 ego_head);
@@ -695,7 +783,11 @@ update_identities(void *cls,
     //Starting over. We must update the Attributes for they might have changed.
     ns_it = GNUNET_NAMESTORE_zone_iteration_start (ns_handle,
                                                    priv_key,
+                                                   &attribute_collect_error_cb,
+                                                   next_ego,
                                                    &attribute_collect,
+                                                   next_ego,
+                                                   &attribute_collect_finished_cb,
                                                    next_ego);
 
   }
@@ -705,13 +797,16 @@ update_identities(void *cls,
     next_ego->attributes_dirty = GNUNET_YES;
     ns_it = GNUNET_NAMESTORE_zone_iteration_start (ns_handle,
                                                    priv_key,
+                                                   &token_collect_error_cb,
+                                                   next_ego,
                                                    &token_collect,
+                                                   next_ego,
+                                                   &token_collect_finished_cb,
                                                    next_ego);
   }
 }
 
 
-
 /**
  * Function called initially to start update task
  */
@@ -720,9 +815,11 @@ init_cont ()
 {
   GNUNET_log (GNUNET_ERROR_TYPE_INFO, ">>> Starting Service\n");
   //Initially iterate all itenties and refresh all tokens
-  update_task = GNUNET_SCHEDULER_add_now (&update_identities, ego_head);
+  update_task = GNUNET_SCHEDULER_add_now (&update_identities,
+                                          ego_head);
 }
 
+
 /**
  * Initial ego collection function.
  *
@@ -765,11 +862,6 @@ cleanup()
 
   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
               "Cleaning up\n");
-  if (NULL != nc)
-  {
-    GNUNET_SERVER_notification_context_destroy (nc);
-    nc = NULL;
-  }
   if (NULL != stats)
   {
     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
@@ -819,8 +911,7 @@ cleanup()
  * @param tc task context
  */
 static void
-do_shutdown (void *cls,
-             const struct GNUNET_SCHEDULER_TaskContext *tc)
+do_shutdown (void *cls)
 {
   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
               "Shutting down...\n");
@@ -828,134 +919,157 @@ do_shutdown (void *cls,
 }
 
 
-static struct GNUNET_IDENTITY_PROVIDER_ExchangeResultMessage*
+static struct GNUNET_MQ_Envelope*
 create_exchange_result_message (const char* token,
-                                const char* label)
+                                const char* label,
+                                uint64_t ticket_nonce,
+                                uint64_t id)
 {
-  struct GNUNET_IDENTITY_PROVIDER_ExchangeResultMessage *erm;
+  struct GNUNET_MQ_Envelope *env;
+  struct ExchangeResultMessage *erm;
   uint16_t token_len = strlen (token) + 1;
-  erm = GNUNET_malloc (sizeof (struct GNUNET_IDENTITY_PROVIDER_ExchangeResultMessage) 
-                       + token_len);
-  erm->header.type = htons (GNUNET_MESSAGE_TYPE_IDENTITY_PROVIDER_EXCHANGE_RESULT);
-  erm->header.size = htons (sizeof (struct GNUNET_IDENTITY_PROVIDER_ExchangeResultMessage) 
-                            + token_len);
-  memcpy (&erm[1], token, token_len);
-  return erm;
+
+  env = GNUNET_MQ_msg_extra (erm,
+                             token_len,
+                             GNUNET_MESSAGE_TYPE_IDENTITY_PROVIDER_EXCHANGE_RESULT);
+  erm->ticket_nonce = htonl (ticket_nonce);
+  erm->id = id;
+  GNUNET_memcpy (&erm[1], token, token_len);
+  return env;
 }
 
 
-static struct GNUNET_IDENTITY_PROVIDER_IssueResultMessage*
-create_issue_result_message (const char* ticket)
+static struct GNUNET_MQ_Envelope*
+create_issue_result_message (const char* label,
+                             const char* ticket,
+                             const char* token,
+                             uint64_t id)
 {
-  struct GNUNET_IDENTITY_PROVIDER_IssueResultMessage *irm;
+  struct GNUNET_MQ_Envelope *env;
+  struct IssueResultMessage *irm;
+  char *tmp_str;
+  size_t len;
+
+  GNUNET_asprintf (&tmp_str, "%s,%s,%s", label, ticket, token);
+  len = strlen (tmp_str) + 1;
+  env = GNUNET_MQ_msg_extra (irm,
+                             len,
+                             GNUNET_MESSAGE_TYPE_IDENTITY_PROVIDER_ISSUE_RESULT);
+  irm->id = id;
+  GNUNET_memcpy (&irm[1], tmp_str, strlen (tmp_str) + 1);
+  GNUNET_free (tmp_str);
+  return env;
+}
 
-  irm = GNUNET_malloc (sizeof (struct GNUNET_IDENTITY_PROVIDER_IssueResultMessage) + strlen(ticket) + 1);
-  irm->header.type = htons (GNUNET_MESSAGE_TYPE_IDENTITY_PROVIDER_ISSUE_RESULT);
-  irm->header.size = htons (sizeof (struct GNUNET_IDENTITY_PROVIDER_IssueResultMessage) + strlen (ticket) + 1);
-  memcpy (&irm[1], ticket, strlen (ticket) + 1);
-  return irm;
+static void
+cleanup_issue_handle (struct IssueHandle *handle)
+{
+  if (NULL != handle->attr_map)
+    GNUNET_CONTAINER_multihashmap_destroy (handle->attr_map);
+  if (NULL != handle->scopes)
+    GNUNET_free (handle->scopes);
+  if (NULL != handle->token)
+    token_destroy (handle->token);
+  if (NULL != handle->ticket)
+    ticket_destroy (handle->ticket);
+  if (NULL != handle->label)
+    GNUNET_free (handle->label);
+  GNUNET_free (handle);
 }
 
-void
+static void
 store_token_issue_cont (void *cls,
                         int32_t success,
                         const char *emsg)
 {
   struct IssueHandle *handle = cls;
-  struct GNUNET_IDENTITY_PROVIDER_IssueResultMessage *irm;
-  char* token_ticket_str;
+  struct GNUNET_MQ_Envelope *env;
+  char *ticket_str;
+  char *token_str;
+
   handle->ns_qe = NULL;
   if (GNUNET_SYSERR == success)
   {
-    //TODO err msg
+    cleanup_issue_handle (handle);
+    GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s\n",
+                "Unknown Error\n");
+    GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
     return;
   }
   if (GNUNET_OK != ticket_serialize (handle->ticket,
                                      &handle->iss_key,
-                                     &token_ticket_str))
+                                     &ticket_str))
   {
-    GNUNET_CONTAINER_multihashmap_destroy (handle->attr_map);
-    ticket_destroy (handle->ticket);
-    GNUNET_free (handle);
-    GNUNET_SCHEDULER_add_now (&do_shutdown, NULL); 
+    GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s\n",
+                "Error serializing ticket\n");
+    cleanup_issue_handle (handle);
+    GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
+    return;
+  }
+  if (GNUNET_OK != token_to_string (handle->token,
+                                    &handle->iss_key,
+                                    &token_str))
+  {
+    GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s\n",
+                "Error serializing token\n");
+    GNUNET_free (ticket_str);
+    cleanup_issue_handle (handle);
+    GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
     return;
   }
-  irm = create_issue_result_message (token_ticket_str);
-  GNUNET_SERVER_notification_context_unicast (nc,
-                                              handle->client,
-                                              &irm->header,
-                                              GNUNET_NO);
-  GNUNET_free (irm);
-  GNUNET_free (token_ticket_str);
-  GNUNET_SERVER_receive_done (handle->client, GNUNET_OK);
+  env = create_issue_result_message (handle->label,
+                                     ticket_str,
+                                     token_str,
+                                     handle->r_id);
+  GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq(handle->client),
+                  env);
+  cleanup_issue_handle (handle);
+  GNUNET_free (ticket_str);
+  GNUNET_free (token_str);
 }
 
+
 /**
- * Build a GNUid token for identity
- * @param handle the handle
- * @param ego_entry the ego to build the token for
- * @param name name of the ego
- * @param token_aud token audience
- * @param token the resulting gnuid token
- * @return identifier string of token (label)
+ * Build a token and store it
+ *
+ * @param cls the IssueHandle
  */
 static void
-sign_and_return_token (void *cls,
-                       const struct GNUNET_SCHEDULER_TaskContext *tc)
+sign_and_return_token (void *cls)
 {
   struct GNUNET_CRYPTO_EcdsaPublicKey pub_key;
-  struct GNUNET_CRYPTO_EcdsaPublicKey aud_pkey;
   struct GNUNET_CRYPTO_EcdhePrivateKey *ecdhe_privkey;
   struct IssueHandle *handle = cls;
   struct GNUNET_GNSRECORD_Data token_record[2];
-  struct GNUNET_TIME_Relative etime_rel;
-  char *lbl_str;
   char *nonce_str;
   char *enc_token_str;
   char *token_metadata;
   char* write_ptr;
   uint64_t time;
   uint64_t exp_time;
-  uint64_t rnd_key;
   size_t token_metadata_len;
 
-  //Remote nonce 
+  //Remote nonce
   nonce_str = NULL;
-  GNUNET_asprintf (&nonce_str, "%d", handle->nonce);
+  GNUNET_asprintf (&nonce_str, "%lu", handle->nonce);
   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Request nonce: %s\n", nonce_str);
 
-  //Label
-  rnd_key = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG, UINT64_MAX);
-  GNUNET_STRINGS_base64_encode ((char*)&rnd_key, sizeof (uint64_t), &lbl_str);
   GNUNET_CRYPTO_ecdsa_key_get_public (&handle->iss_key,
                                       &pub_key);
-
-  handle->ticket = ticket_create (nonce_str,
+  handle->ticket = ticket_create (handle->nonce,
                                   &pub_key,
-                                  lbl_str,
-                                  &aud_pkey);
+                                  handle->label,
+                                  &handle->aud_key);
 
-
-
-  if (GNUNET_OK !=
-      GNUNET_STRINGS_fancy_time_to_relative ("1d", //TODO
-                                             &etime_rel))
-  {
-    ticket_destroy (handle->ticket);
-    GNUNET_free (handle);
-    GNUNET_SCHEDULER_add_now (&do_shutdown, handle);
-    return;
-  }
   time = GNUNET_TIME_absolute_get().abs_value_us;
-  exp_time = time + etime_rel.rel_value_us;
+  exp_time = time + token_expiration_interval.rel_value_us;
 
-  token_add_json (handle->token, "nbf", json_integer (time));
-  token_add_json (handle->token, "iat", json_integer (time));
-  token_add_json (handle->token, "exp", json_integer (exp_time));
+  token_add_attr_int (handle->token, "nbf", time);
+  token_add_attr_int (handle->token, "iat", time);
+  token_add_attr_int (handle->token, "exp", exp_time);
   token_add_attr (handle->token, "nonce", nonce_str);
 
-
-  //Token in a serialized encrypted format 
+  //Token in a serialized encrypted format
   GNUNET_assert (token_serialize (handle->token,
                                   &handle->iss_key,
                                   &ecdhe_privkey,
@@ -974,13 +1088,11 @@ sign_and_return_token (void *cls,
     + strlen (handle->scopes) + 1; //With 0-Terminator
   token_metadata = GNUNET_malloc (token_metadata_len);
   write_ptr = token_metadata;
-  memcpy (token_metadata, ecdhe_privkey, sizeof (struct GNUNET_CRYPTO_EcdhePrivateKey));
+  GNUNET_memcpy (token_metadata, ecdhe_privkey, sizeof (struct GNUNET_CRYPTO_EcdhePrivateKey));
   write_ptr += sizeof (struct GNUNET_CRYPTO_EcdhePrivateKey);
-  memcpy (write_ptr, &handle->aud_key, sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey));
+  GNUNET_memcpy (write_ptr, &handle->aud_key, sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey));
   write_ptr += sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey);
-  memcpy (write_ptr, handle->scopes, strlen (handle->scopes) + 1); //with 0-Terminator;
-
-  GNUNET_free (ecdhe_privkey);
+  GNUNET_memcpy (write_ptr, handle->scopes, strlen (handle->scopes) + 1); //with 0-Terminator;
 
   token_record[1].data = token_metadata;
   token_record[1].data_size = token_metadata_len;
@@ -991,15 +1103,40 @@ sign_and_return_token (void *cls,
   //Persist token
   handle->ns_qe = GNUNET_NAMESTORE_records_store (ns_handle,
                                                   &handle->iss_key,
-                                                  lbl_str,
+                                                  handle->label,
                                                   2,
                                                   token_record,
                                                   &store_token_issue_cont,
                                                   handle);
-  GNUNET_free (lbl_str);
+  GNUNET_free (ecdhe_privkey);
+  GNUNET_free (nonce_str);
   GNUNET_free (enc_token_str);
+  GNUNET_free (token_metadata);
 }
 
+
+static void
+attr_collect_error (void *cls)
+{
+  struct IssueHandle *handle = cls;
+
+  GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Adding attribute Error!\n");
+  handle->ns_it = NULL;
+  GNUNET_SCHEDULER_add_now (&sign_and_return_token, handle);
+}
+
+
+static void
+attr_collect_finished (void *cls)
+{
+  struct IssueHandle *handle = cls;
+
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Adding attribute END: \n");
+  handle->ns_it = NULL;
+  GNUNET_SCHEDULER_add_now (&sign_and_return_token, handle);
+}
+
+
 /**
  * Collect attributes for token
  */
@@ -1010,20 +1147,11 @@ attr_collect (void *cls,
               unsigned int rd_count,
               const struct GNUNET_GNSRECORD_Data *rd)
 {
+  struct IssueHandle *handle = cls;
   int i;
   char* data;
-  json_t *attr_arr;
-  struct IssueHandle *handle = cls;
   struct GNUNET_HashCode key;
 
-  if (NULL == label)
-  {
-    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Adding attribute END: \n");
-    handle->ns_it = NULL;
-    GNUNET_SCHEDULER_add_now (&sign_and_return_token, handle);
-    return;
-  }
-
   GNUNET_CRYPTO_hash (label,
                       strlen (label),
                       &key);
@@ -1049,9 +1177,9 @@ attr_collect (void *cls,
                                                rd->data,
                                                rd->data_size);
       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Adding value: %s\n", data);
-      token_add_json (handle->token,
+      token_add_attr (handle->token,
                       label,
-                      json_string (data));
+                      data);
       GNUNET_free (data);
     }
     GNUNET_NAMESTORE_zone_iterator_next (handle->ns_it);
@@ -1059,7 +1187,6 @@ attr_collect (void *cls,
   }
 
   i = 0;
-  attr_arr = json_array();
   for (; i < rd_count; i++)
   {
     if (rd->record_type == GNUNET_GNSRECORD_TYPE_ID_ATTR)
@@ -1068,25 +1195,30 @@ attr_collect (void *cls,
                                                rd[i].data,
                                                rd[i].data_size);
       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Adding value: %s\n", data);
-      json_array_append_new (attr_arr, json_string (data));
+      token_add_attr (handle->token, label, data);
       GNUNET_free (data);
     }
   }
 
-  if (0 < json_array_size (attr_arr))
-  {
-    token_add_json (handle->token, label, attr_arr);
-  }
-  json_decref (attr_arr);
   GNUNET_NAMESTORE_zone_iterator_next (handle->ns_it);
 }
 
+static void
+cleanup_exchange_handle (struct ExchangeHandle *handle)
+{
+  if (NULL != handle->ticket)
+    ticket_destroy (handle->ticket);
+  if (NULL != handle->token)
+    token_destroy (handle->token);
+  GNUNET_free (handle);
+}
+
 static void
 process_lookup_result (void *cls, uint32_t rd_count,
                        const struct GNUNET_GNSRECORD_Data *rd)
 {
   struct ExchangeHandle *handle = cls;
-  struct GNUNET_IDENTITY_PROVIDER_ExchangeResultMessage *erm;
+  struct GNUNET_MQ_Envelope *env;
   char* token_str;
   char* record_str;
 
@@ -1096,13 +1228,12 @@ process_lookup_result (void *cls, uint32_t rd_count,
     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                 "Number of tokens %d != 2.",
                 rd_count);
-    GNUNET_free (handle->label);
-    GNUNET_free (handle);
-    GNUNET_SCHEDULER_add_now (&do_shutdown, handle);
+    cleanup_exchange_handle (handle);
+    GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
     return;
   }
 
-  record_str = 
+  record_str =
     GNUNET_GNSRECORD_value_to_string (GNUNET_GNSRECORD_TYPE_ID_TOKEN,
                                       rd->data,
                                       rd->data_size);
@@ -1117,15 +1248,37 @@ process_lookup_result (void *cls, uint32_t rd_count,
                                                &handle->aud_privkey,
                                                &token_str));
 
-  erm = create_exchange_result_message (token_str,
-                                        handle->label);
-  GNUNET_SERVER_notification_context_unicast (nc,
-                                              handle->client,
-                                              &erm->header,
-                                              GNUNET_NO);
-  GNUNET_free (erm);
-  GNUNET_SERVER_receive_done (handle->client, GNUNET_OK);
+  env = create_exchange_result_message (token_str,
+                                        handle->label,
+                                        handle->ticket->payload->nonce,
+                                        handle->r_id);
+  GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq(handle->client),
+                  env);
+  cleanup_exchange_handle (handle);
+  GNUNET_free (record_str);
+  GNUNET_free (token_str);
+}
+
+/**
+ * Checks a exchange message
+ *
+ * @param cls client sending the message
+ * @param xm message of type `struct ExchangeMessage`
+ * @return #GNUNET_OK if @a xm is well-formed
+ */
+static int
+check_exchange_message (void *cls,
+                        const struct ExchangeMessage *xm)
+{
+  uint16_t size;
 
+  size = ntohs (xm->header.size);
+  if (size <= sizeof (struct ExchangeMessage))
+  {
+    GNUNET_break (0);
+    return GNUNET_SYSERR;
+  }
+  return GNUNET_OK;
 }
 
 /**
@@ -1138,55 +1291,231 @@ process_lookup_result (void *cls, uint32_t rd_count,
  */
 static void
 handle_exchange_message (void *cls,
-                         struct GNUNET_SERVER_Client *client,
-                         const struct GNUNET_MessageHeader *message)
+                         const struct ExchangeMessage *xm)
 {
-  const struct GNUNET_IDENTITY_PROVIDER_ExchangeMessage *em;
   struct ExchangeHandle *xchange_handle;
-  uint16_t size;
+  struct GNUNET_SERVICE_Client *client = cls;
   const char *ticket;
   char *lookup_query;
 
-  size = ntohs (message->size);
-  if (size <= sizeof (struct GNUNET_IDENTITY_PROVIDER_ExchangeMessage))
-  {
-    GNUNET_break (0);
-    GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
-    return;
-  }
-  em = (const struct GNUNET_IDENTITY_PROVIDER_ExchangeMessage *) message;
-  ticket = (const char *) &em[1];
+  ticket = (const char *) &xm[1];
   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
               "Received EXCHANGE of `%s' from client\n",
               ticket);
   xchange_handle = GNUNET_malloc (sizeof (struct ExchangeHandle));
-  xchange_handle->aud_privkey = em->aud_privkey;
+  xchange_handle->aud_privkey = xm->aud_privkey;
+  xchange_handle->r_id = xm->id;
   if (GNUNET_SYSERR == ticket_parse (ticket,
                                      &xchange_handle->aud_privkey,
                                      &xchange_handle->ticket))
   {
     GNUNET_free (xchange_handle);
-    GNUNET_break (0);
-    GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
+    GNUNET_SERVICE_client_drop (client);
     return;
   }
-  GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Looking for token under %s\n",
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Looking for token under %s\n",
               xchange_handle->ticket->payload->label);
   GNUNET_asprintf (&lookup_query,
                    "%s.gnu",
                    xchange_handle->ticket->payload->label);
-  xchange_handle->lookup_request = GNUNET_GNS_lookup (gns_handle,
-                                                      lookup_query,
-                                                      &xchange_handle->ticket->payload->identity_key,
-                                                      GNUNET_GNSRECORD_TYPE_ID_TOKEN,
-                                                      GNUNET_GNS_LO_LOCAL_MASTER,
-                                                      NULL,
-                                                      &process_lookup_result,
-                                                      xchange_handle);
+  GNUNET_SERVICE_client_continue (client);
+  xchange_handle->client = client;
+  xchange_handle->lookup_request
+    = GNUNET_GNS_lookup (gns_handle,
+                         lookup_query,
+                         &xchange_handle->ticket->payload->identity_key,
+                         GNUNET_GNSRECORD_TYPE_ID_TOKEN,
+                         GNUNET_GNS_LO_LOCAL_MASTER,
+                         &process_lookup_result,
+                         xchange_handle);
   GNUNET_free (lookup_query);
 
 }
 
+
+static void
+find_existing_token_error (void *cls)
+{
+  struct IssueHandle *handle = cls;
+  cleanup_issue_handle (handle);
+  GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Error looking for existing token\n");
+  GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
+}
+
+
+static void
+find_existing_token_finished (void *cls)
+{
+  struct IssueHandle *handle = cls;
+  uint64_t rnd_key;
+
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+              ">>> No existing token found\n");
+  rnd_key =
+    GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
+                              UINT64_MAX);
+  GNUNET_STRINGS_base64_encode ((char*)&rnd_key,
+                                sizeof (uint64_t),
+                                &handle->label);
+  handle->ns_it = NULL;
+  handle->ns_it = GNUNET_NAMESTORE_zone_iteration_start (ns_handle,
+                                                         &handle->iss_key,
+                                                         &attr_collect_error,
+                                                         handle,
+                                                         &attr_collect,
+                                                         handle,
+                                                         &attr_collect_finished,
+                                                         handle);
+}
+
+
+/**
+ *
+ * Look for existing token
+ *
+ * @param cls the identity entry
+ * @param zone the identity
+ * @param lbl the name of the record
+ * @param rd_count number of records
+ * @param rd record data
+ *
+ */
+static void
+find_existing_token (void *cls,
+                     const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
+                     const char *lbl,
+                     unsigned int rd_count,
+                     const struct GNUNET_GNSRECORD_Data *rd)
+{
+  struct IssueHandle *handle = cls;
+  const struct GNUNET_GNSRECORD_Data *token_metadata_record;
+  struct GNUNET_CRYPTO_EcdsaPublicKey *aud_key;
+  struct GNUNET_HashCode key;
+  int scope_count_token;
+  char *scope;
+  char *tmp_scopes;
+
+  //There should be only a single record for a token under a label
+  if (2 != rd_count)
+  {
+    GNUNET_NAMESTORE_zone_iterator_next (handle->ns_it);
+    return;
+  }
+
+  if (rd[0].record_type == GNUNET_GNSRECORD_TYPE_ID_TOKEN_METADATA)
+  {
+    token_metadata_record = &rd[0];
+  }
+  else
+  {
+    token_metadata_record = &rd[1];
+  }
+  if (token_metadata_record->record_type != GNUNET_GNSRECORD_TYPE_ID_TOKEN_METADATA)
+  {
+    GNUNET_NAMESTORE_zone_iterator_next (handle->ns_it);
+    return;
+  }
+  ecdhe_privkey = *((struct GNUNET_CRYPTO_EcdhePrivateKey *)token_metadata_record->data);
+  aud_key =
+    (struct GNUNET_CRYPTO_EcdsaPublicKey *)(token_metadata_record->data+sizeof(struct GNUNET_CRYPTO_EcdhePrivateKey));
+  tmp_scopes = GNUNET_strdup ((char*) aud_key+sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey));
+
+  if (0 != memcmp (aud_key, &handle->aud_key,
+                   sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey)))
+  {
+    char *tmp2 = GNUNET_STRINGS_data_to_string_alloc (aud_key,
+                                                      sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey));
+    //Audience does not match!
+    char *tmp = GNUNET_GNSRECORD_value_to_string (GNUNET_GNSRECORD_TYPE_ID_TOKEN_METADATA,
+                                                  token_metadata_record->data,
+                                                  token_metadata_record->data_size);
+    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                "Token does not match audience %s vs %s. Moving on\n",
+                tmp2,
+                tmp);
+    GNUNET_free (tmp_scopes);
+    GNUNET_free (tmp2);
+    GNUNET_free (tmp);
+    GNUNET_NAMESTORE_zone_iterator_next (handle->ns_it);
+    return;
+  }
+
+  scope = strtok (tmp_scopes, ",");
+  scope_count_token = 0;
+  while (NULL != scope)
+  {
+    GNUNET_CRYPTO_hash (scope,
+                        strlen (scope),
+                        &key);
+
+    if ((NULL != handle->attr_map) &&
+        (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains (handle->attr_map, &key)))
+    {
+      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                  "Issued token does not include `%s'. Moving on\n", scope);
+      GNUNET_free (tmp_scopes);
+      GNUNET_NAMESTORE_zone_iterator_next (handle->ns_it);
+      return;
+    }
+    scope_count_token++;
+    scope = strtok (NULL, ",");
+  }
+  GNUNET_free (tmp_scopes);
+  //All scopes in token are also in request. Now
+  //Check length
+  if ((NULL != handle->attr_map) &&
+      (GNUNET_CONTAINER_multihashmap_size (handle->attr_map) == scope_count_token))
+  {
+    //We have an existing token
+    handle->label = GNUNET_strdup (lbl);
+    handle->ns_it = NULL;
+    handle->ns_it = GNUNET_NAMESTORE_zone_iteration_start (ns_handle,
+                                                           &handle->iss_key,
+                                                           &attr_collect_error,
+                                                           handle,
+                                                           &attr_collect,
+                                                           handle,
+                                                           &attr_collect_finished,
+                                                           handle);
+
+    return;
+  }
+  GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
+              "Nuber of attributes in token do not match request\n");
+  //No luck
+  GNUNET_NAMESTORE_zone_iterator_next (handle->ns_it);
+}
+
+/**
+ * Checks an issue message
+ *
+ * @param cls client sending the message
+ * @param im message of type `struct IssueMessage`
+ * @return #GNUNET_OK if @a im is well-formed
+ */
+static int
+check_issue_message(void *cls,
+                    const struct IssueMessage *im)
+{
+  uint16_t size;
+
+  size = ntohs (im->header.size);
+  if (size <= sizeof (struct IssueMessage))
+  {
+    GNUNET_break (0);
+    return GNUNET_SYSERR;
+  }
+  scopes = (char *) &im[1];
+  if ('\0' != scopes[size - sizeof (struct IssueMessage) - 1])
+  {
+    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
+                "Malformed scopes received!\n");
+    GNUNET_break (0);
+    return GNUNET_SYSERR;
+  }
+  return GNUNET_OK;
+}
+
 /**
  *
  * Handler for issue message
@@ -1197,35 +1526,22 @@ handle_exchange_message (void *cls,
  */
 static void
 handle_issue_message (void *cls,
-                      struct GNUNET_SERVER_Client *client,
-                      const struct GNUNET_MessageHeader *message)
+                      const struct IssueMessage *im)
 {
-  const struct GNUNET_IDENTITY_PROVIDER_IssueMessage *im;
-  uint16_t size;
   const char *scopes;
   char *scopes_tmp;
   char *scope;
   struct GNUNET_HashCode key;
   struct IssueHandle *issue_handle;
+  struct GNUNET_SERVICE_Client *client = cls;
 
-  size = ntohs (message->size);
-  if (size <= sizeof (struct GNUNET_IDENTITY_PROVIDER_IssueMessage))
-  {
-    GNUNET_break (0);
-    GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
-    return;
-  }
-  im = (const struct GNUNET_IDENTITY_PROVIDER_IssueMessage *) message;
   scopes = (const char *) &im[1];
-  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
-              "Received ISSUE of `%s' from client\n",
-              scope);
   issue_handle = GNUNET_malloc (sizeof (struct IssueHandle));
   issue_handle->attr_map = GNUNET_CONTAINER_multihashmap_create (5,
                                                                  GNUNET_NO);
   scopes_tmp = GNUNET_strdup (scopes);
-  scope = strtok(scopes_tmp, ",");
-  for (; NULL != scope; scope = strtok (NULL, ","))
+
+  for (scope = strtok (scopes_tmp, ","); NULL != scope; scope = strtok (NULL, ","))
   {
     GNUNET_CRYPTO_hash (scope,
                         strlen (scope),
@@ -1236,25 +1552,30 @@ handle_issue_message (void *cls,
                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
   }
   GNUNET_free (scopes_tmp);
-
+  issue_handle->r_id = im->id;
   issue_handle->aud_key = im->aud_key;
   issue_handle->iss_key = im->iss_key;
-  issue_handle->expiration = GNUNET_TIME_absolute_ntoh (im->expiration);
-  issue_handle->nonce = im->nonce;
   GNUNET_CRYPTO_ecdsa_key_get_public (&im->iss_key,
                                       &issue_handle->iss_pkey);
+  issue_handle->expiration = GNUNET_TIME_absolute_ntoh (im->expiration);
+  issue_handle->nonce = ntohl (im->nonce);
+  GNUNET_SERVICE_client_continue (client);
+  issue_handle->client = client;
+  issue_handle->scopes = GNUNET_strdup (scopes);
   issue_handle->token = token_create (&issue_handle->iss_pkey,
-                                      &im->aud_key);
+                                      &issue_handle->aud_key);
 
   issue_handle->ns_it = GNUNET_NAMESTORE_zone_iteration_start (ns_handle,
                                                                &im->iss_key,
-                                                               &attr_collect,
+                                                               &find_existing_token_error,
+                                                               issue_handle,
+                                                               &find_existing_token,
+                                                               issue_handle,
+                                                               &find_existing_token_finished,
                                                                issue_handle);
-  GNUNET_SERVER_receive_done (client, GNUNET_OK); //TODO here?
-
-
 }
 
+
 /**
  * Main function that will be run
  *
@@ -1264,23 +1585,13 @@ handle_issue_message (void *cls,
  * @param c configuration
  */
 static void
-run (void *cls, 
-     struct GNUNET_SERVER_Handle *server,
-     const struct GNUNET_CONFIGURATION_Handle *c)
+run (void *cls,
+     const struct GNUNET_CONFIGURATION_Handle *c,
+     struct GNUNET_SERVICE_Handle *server)
 {
-  static const struct GNUNET_SERVER_MessageHandler handlers[] = {
-    {&handle_issue_message, NULL,
-      GNUNET_MESSAGE_TYPE_IDENTITY_PROVIDER_ISSUE, 0},
-    {&handle_exchange_message, NULL,
-      GNUNET_MESSAGE_TYPE_IDENTITY_PROVIDER_EXCHANGE, 0},
-    {NULL, NULL, 0, 0}
-  };
-
   cfg = c;
 
   stats = GNUNET_STATISTICS_create ("identity-provider", cfg);
-  GNUNET_SERVER_add_handlers (server, handlers);
-  nc = GNUNET_SERVER_notification_context_create (server, 1);
 
   //Connect to identity and namestore services
   ns_handle = GNUNET_NAMESTORE_connect (cfg);
@@ -1299,27 +1610,79 @@ run (void *cls,
                                              &list_ego,
                                              NULL);
 
-  GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
-                                &do_shutdown, NULL);
-}
+  if (GNUNET_OK ==
+      GNUNET_CONFIGURATION_get_value_time (cfg,
+                                           "identity-provider",
+                                           "TOKEN_EXPIRATION_INTERVAL",
+                                           &token_expiration_interval))
+  {
+    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                "Time window for zone iteration: %s\n",
+                GNUNET_STRINGS_relative_time_to_string (token_expiration_interval,
+                                                        GNUNET_YES));
+  } else {
+    token_expiration_interval = DEFAULT_TOKEN_EXPIRATION_INTERVAL;
+  }
 
+  GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL);
+}
 
 /**
+ * Called whenever a client is disconnected.
  *
- * The main function
- *
- * @param argc number of arguments from the cli
- * @param argv command line arguments
- * @return 0 ok, 1 on error
+ * @param cls closure
+ * @param client identification of the client
+ * @param app_ctx @a client
+ */
+static void
+client_disconnect_cb (void *cls,
+                      struct GNUNET_SERVICE_Client *client,
+                      void *app_ctx)
+{
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+              "Client %p disconnected\n",
+              client);
+}
+
+
+/**
+ * Add a client to our list of active clients.
  *
+ * @param cls NULL
+ * @param client client to add
+ * @param mq message queue for @a client
+ * @return internal namestore client structure for this client
  */
-int
-main (int argc, char *const *argv)
+static void *
+client_connect_cb (void *cls,
+                   struct GNUNET_SERVICE_Client *client,
+                   struct GNUNET_MQ_Handle *mq)
 {
-  return  (GNUNET_OK ==
-           GNUNET_SERVICE_run (argc, argv, "identity-provider",
-                               GNUNET_SERVICE_OPTION_NONE,
-                               &run, NULL)) ? 0 : 1;
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+              "Client %p connected\n",
+              client);
+  return client;
 }
 
-/* end of gnunet-rest-server.c */
+
+
+/**
+ * Define "main" method using service macro.
+ */
+GNUNET_SERVICE_MAIN
+("identity-provider",
+ GNUNET_SERVICE_OPTION_NONE,
+ &run,
+ &client_connect_cb,
+ &client_disconnect_cb,
+ NULL,
+ GNUNET_MQ_hd_var_size (issue_message,
+                        GNUNET_MESSAGE_TYPE_IDENTITY_PROVIDER_ISSUE,
+                        struct IssueMessage,
+                        NULL),
+ GNUNET_MQ_hd_var_size (exchange_message,
+                        GNUNET_MESSAGE_TYPE_IDENTITY_PROVIDER_EXCHANGE,
+                        struct ExchangeMessage,
+                        NULL),
+ GNUNET_MQ_handler_end());
+/* end of gnunet-service-identity-provider.c */