- coverity
[oweals/gnunet.git] / src / namestore / gnunet-service-namestore.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file namestore/gnunet-service-namestore.c
23  * @brief namestore for the GNUnet naming system
24  * @author Matthias Wachs
25  */
26 #include "platform.h"
27 #include "gnunet_getopt_lib.h"
28 #include "gnunet_service_lib.h"
29 #include "gnunet_namestore_service.h"
30 #include "gnunet_namestore_plugin.h"
31 #include "gnunet_signatures.h"
32 #include "namestore.h"
33
34 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
35
36 /**
37  * A namestore operation.
38  */
39 struct GNUNET_NAMESTORE_ZoneIteration
40 {
41   struct GNUNET_NAMESTORE_ZoneIteration *next;
42   struct GNUNET_NAMESTORE_ZoneIteration *prev;
43
44   struct GNUNET_NAMESTORE_Client * client;
45
46   int has_zone;
47
48   struct GNUNET_CRYPTO_ShortHashCode zone;
49
50   uint64_t request_id;
51   uint32_t offset;
52
53
54
55 };
56
57
58 /**
59  * A namestore client
60  */
61 struct GNUNET_NAMESTORE_Client
62 {
63   struct GNUNET_NAMESTORE_Client *next;
64   struct GNUNET_NAMESTORE_Client *prev;
65
66   struct GNUNET_SERVER_Client * client;
67
68   struct GNUNET_NAMESTORE_ZoneIteration *op_head;
69   struct GNUNET_NAMESTORE_ZoneIteration *op_tail;
70 };
71
72 struct GNUNET_NAMESTORE_CryptoContainer
73 {
74   char * filename;
75
76   struct GNUNET_CRYPTO_ShortHashCode zone;
77   struct GNUNET_CRYPTO_RsaPrivateKey *privkey;
78   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pubkey;
79 };
80
81
82 /**
83 * Configuration handle.
84 */
85 const struct GNUNET_CONFIGURATION_Handle *GSN_cfg;
86
87 /**
88 * Database handle
89 */
90 struct GNUNET_NAMESTORE_PluginFunctions *GSN_database;
91
92 /**
93 * Zonefile directory
94 */
95 static char *zonefile_directory;
96
97 static char *db_lib_name;
98
99
100 /**
101  * Our notification context.
102  */
103 static struct GNUNET_SERVER_NotificationContext *snc;
104
105 static struct GNUNET_NAMESTORE_Client *client_head;
106 static struct GNUNET_NAMESTORE_Client *client_tail;
107
108 struct GNUNET_CONTAINER_MultiHashMap *zonekeys;
109
110
111 /**
112  * Write zonefile to disk
113  * @param filename where to write
114  * @param c the crypto container
115  *
116  * @return GNUNET_OK on success, GNUNET_SYSERR on fail
117  */
118
119 int
120 write_key_to_file (const char *filename, struct GNUNET_NAMESTORE_CryptoContainer *c)
121 {
122   struct GNUNET_CRYPTO_RsaPrivateKey *ret = c->privkey;
123   struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *enc;
124   struct GNUNET_DISK_FileHandle *fd;
125
126   if (GNUNET_YES == GNUNET_DISK_file_test (filename))
127   {
128     struct GNUNET_CRYPTO_ShortHashCode zone;
129     struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pubkey;
130     struct GNUNET_CRYPTO_RsaPrivateKey * privkey;
131
132     privkey = GNUNET_CRYPTO_rsa_key_create_from_file(filename);
133     if (privkey == NULL)
134     {
135       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
136            _("File zone `%s' but corrupt content already exists, failed to write! \n"), GNUNET_short_h2s (&zone));
137       return GNUNET_SYSERR;
138     }
139
140     GNUNET_CRYPTO_rsa_key_get_public (privkey, &pubkey);
141     GNUNET_CRYPTO_short_hash (&pubkey, sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded), &zone);
142     GNUNET_CRYPTO_rsa_key_free (privkey);
143
144     if (0 == memcmp (&zone, &c->zone, sizeof(zone)))
145     {
146       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
147            _("File zone `%s' containing this key already exists\n"), GNUNET_short_h2s (&zone));
148       return GNUNET_OK;
149     }
150     else
151     {
152       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
153            _("File zone `%s' but different zone key already exists, failed to write! \n"), GNUNET_short_h2s (&zone));
154       return GNUNET_OK;
155     }
156   }
157   fd = GNUNET_DISK_file_open (filename, GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE | GNUNET_DISK_OPEN_FAILIFEXISTS, GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE);
158   if (NULL == fd)
159   {
160     if (errno == EEXIST)
161     {
162       if (GNUNET_YES != GNUNET_DISK_file_test (filename))
163       {
164         /* must exist but not be accessible, fail for good! */
165         if (0 != ACCESS (filename, R_OK))
166           LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename);
167         else
168           GNUNET_break (0);   /* what is going on!? */
169         return GNUNET_SYSERR;
170       }
171     }
172     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
173     return GNUNET_SYSERR;
174   }
175
176   if (GNUNET_YES != GNUNET_DISK_file_lock (fd, 0, sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded), GNUNET_YES))
177   {
178     GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
179     return GNUNET_SYSERR;
180   }
181   enc = GNUNET_CRYPTO_rsa_encode_key (ret);
182   GNUNET_assert (enc != NULL);
183   GNUNET_assert (ntohs (enc->len) == GNUNET_DISK_file_write (fd, enc, ntohs (enc->len)));
184   GNUNET_free (enc);
185   GNUNET_DISK_file_sync (fd);
186   if (GNUNET_YES != GNUNET_DISK_file_unlock (fd, 0, sizeof (struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded)))
187     LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
188   GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
189
190   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
191        _("Stored zonekey for zone `%s' in file `%s'\n"), GNUNET_short_h2s(&c->zone), c->filename);
192   return GNUNET_OK;
193 }
194
195 int zone_to_disk_it (void *cls,
196                      const GNUNET_HashCode *key,
197                      void *value)
198 {
199   struct GNUNET_NAMESTORE_CryptoContainer * c = value;
200   if (c->filename != NULL)
201     write_key_to_file(c->filename, c);
202   else
203   {
204     GNUNET_asprintf(&c->filename, "%s/%s.zkey", zonefile_directory, GNUNET_short_h2s (&c->zone));
205     write_key_to_file(c->filename, c);
206   }
207
208
209   GNUNET_assert (GNUNET_OK == GNUNET_CONTAINER_multihashmap_remove (zonekeys, key, value));
210   GNUNET_CRYPTO_rsa_key_free (c->privkey);
211   GNUNET_free (c->pubkey);
212   GNUNET_free (c->filename);
213   GNUNET_free (c);
214
215   return GNUNET_OK;
216 }
217
218
219 struct GNUNET_TIME_Absolute
220 get_block_expiration_time (unsigned int rd_count, const struct GNUNET_NAMESTORE_RecordData *rd)
221 {
222   int c;
223   struct GNUNET_TIME_Absolute expire = GNUNET_TIME_absolute_get_forever();
224   if (NULL == rd)
225     return GNUNET_TIME_absolute_get_zero();
226   for (c = 0; c < rd_count; c++)
227   {
228     if (rd[c].expiration.abs_value < expire.abs_value)
229       expire = rd[c].expiration;
230   }
231   return expire;
232 }
233
234 /**
235  * Task run during shutdown.
236  *
237  * @param cls unused
238  * @param tc unused
239  */
240 static void
241 cleanup_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
242 {
243   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Stopping namestore service\n");
244   struct GNUNET_NAMESTORE_ZoneIteration * no;
245   struct GNUNET_NAMESTORE_ZoneIteration * tmp;
246   struct GNUNET_NAMESTORE_Client * nc;
247   struct GNUNET_NAMESTORE_Client * next;
248
249   GNUNET_SERVER_notification_context_destroy (snc);
250   snc = NULL;
251   GNUNET_CONTAINER_multihashmap_iterate(zonekeys, &zone_to_disk_it, NULL);
252   GNUNET_CONTAINER_multihashmap_destroy(zonekeys);
253
254   for (nc = client_head; nc != NULL; nc = next)
255   {
256     next = nc->next;
257     for (no = nc->op_head; no != NULL; no = tmp)
258     {
259       GNUNET_CONTAINER_DLL_remove (nc->op_head, nc->op_tail, no);
260       tmp = no->next;
261       GNUNET_free (no);
262     }
263     GNUNET_SERVER_client_drop(nc->client);
264     GNUNET_CONTAINER_DLL_remove (client_head, client_tail, nc);
265     GNUNET_free (nc);
266   }
267
268   GNUNET_break (NULL == GNUNET_PLUGIN_unload (db_lib_name, GSN_database));
269   GNUNET_free (db_lib_name);
270   GNUNET_free_non_null(zonefile_directory);
271 }
272
273 static struct GNUNET_NAMESTORE_Client *
274 client_lookup (struct GNUNET_SERVER_Client *client)
275 {
276   struct GNUNET_NAMESTORE_Client * nc;
277
278   GNUNET_assert (NULL != client);
279
280   for (nc = client_head; nc != NULL; nc = nc->next)
281   {
282     if (client == nc->client)
283       break;
284   }
285   return nc;
286 }
287
288 /**
289  * Called whenever a client is disconnected.  Frees our
290  * resources associated with that client.
291  *
292  * @param cls closure
293  * @param client identification of the client
294  */
295 static void
296 client_disconnect_notification (void *cls, struct GNUNET_SERVER_Client *client)
297 {
298   struct GNUNET_NAMESTORE_ZoneIteration * no;
299   struct GNUNET_NAMESTORE_Client * nc;
300   if (NULL == client)
301     return;
302
303   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client %p disconnected \n", client);
304
305   nc = client_lookup (client);
306
307   if ((NULL == client) || (NULL == nc))
308     return;
309
310   no = nc->op_head;
311   while (NULL != no)
312   {
313     GNUNET_CONTAINER_DLL_remove (nc->op_head, nc->op_tail, no);
314     GNUNET_free (no);
315     no = nc->op_head;
316   }
317
318   GNUNET_SERVER_client_drop(nc->client);
319   GNUNET_CONTAINER_DLL_remove (client_head, client_tail, nc);
320   GNUNET_free (nc);
321   nc = NULL;
322 }
323
324
325
326 static void handle_start (void *cls,
327                           struct GNUNET_SERVER_Client * client,
328                           const struct GNUNET_MessageHeader * message)
329 {
330   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client %p connected\n", client);
331
332   struct GNUNET_NAMESTORE_Client * nc = GNUNET_malloc (sizeof (struct GNUNET_NAMESTORE_Client));
333   nc->client = client;
334   GNUNET_SERVER_notification_context_add (snc, client);
335   GNUNET_CONTAINER_DLL_insert(client_head, client_tail, nc);
336   GNUNET_SERVER_client_keep (client);
337   GNUNET_SERVER_receive_done (client, GNUNET_OK);
338 }
339
340 struct LookupNameContext
341 {
342   struct GNUNET_NAMESTORE_Client *nc;
343   uint32_t request_id;
344   uint32_t record_type;
345   struct GNUNET_CRYPTO_ShortHashCode *zone;
346   char * name;
347 };
348
349 void drop_iterator (void *cls,
350                    const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
351                    struct GNUNET_TIME_Absolute expire,
352                    const char *name,
353                    unsigned int rd_len,
354                    const struct GNUNET_NAMESTORE_RecordData *rd,
355                    const struct GNUNET_CRYPTO_RsaSignature *signature)
356 {
357   struct GNUNET_CRYPTO_ShortHashCode zone_hash;
358   int * stop = cls;
359   if (NULL != zone_key)
360   {
361     GNUNET_CRYPTO_short_hash(zone_key, sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded), &zone_hash);
362     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Deleting zone `%s'\n", GNUNET_short_h2s (&zone_hash));
363     GSN_database->delete_zone (GSN_database->cls, &zone_hash);
364   }
365   else
366   {
367     (*stop) = GNUNET_YES;
368   }
369 }
370
371
372 static void
373 handle_lookup_name_it (void *cls,
374     const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
375     struct GNUNET_TIME_Absolute expire,
376     const char *name,
377     unsigned int rd_count,
378     const struct GNUNET_NAMESTORE_RecordData *rd,
379     const struct GNUNET_CRYPTO_RsaSignature *signature)
380 {
381   /* send response */
382   struct LookupNameContext *lnc = cls;
383   struct LookupNameResponseMessage *lnr_msg;
384   struct GNUNET_NAMESTORE_RecordData *rd_selected = NULL;
385   struct GNUNET_NAMESTORE_CryptoContainer *cc;
386   struct GNUNET_CRYPTO_RsaSignature *signature_new = NULL;
387   struct GNUNET_TIME_Absolute e;
388   struct GNUNET_CRYPTO_ShortHashCode zone_key_hash;
389   GNUNET_HashCode long_hash;
390   char *rd_tmp;
391   char *name_tmp;
392   size_t rd_ser_len;
393   size_t r_size = 0;
394   size_t name_len = 0;
395
396   int copied_elements = 0;
397   int contains_signature = GNUNET_NO;
398   int authoritative = GNUNET_NO;
399   int c;
400
401   if (NULL != name)
402     name_len = strlen(name) + 1;
403
404   /* count records to copy */
405   if (rd_count != 0)
406   {
407     if (lnc->record_type != 0)
408     {
409       /* special record type needed */
410       for (c = 0; c < rd_count; c ++)
411         if (rd[c].record_type == lnc->record_type)
412           copied_elements++; /* found matching record */
413       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found %u records with type %u for name `%s' in zone `%s'\n",
414           copied_elements, lnc->record_type, lnc->name, GNUNET_short_h2s(lnc->zone));
415       rd_selected = GNUNET_malloc (copied_elements * sizeof (struct GNUNET_NAMESTORE_RecordData));
416       copied_elements = 0;
417       for (c = 0; c < rd_count; c ++)
418       {
419         if (rd[c].record_type == lnc->record_type)
420         {
421           /* found matching record */
422           memcpy (&rd_selected[copied_elements], &rd[c], sizeof (struct GNUNET_NAMESTORE_RecordData));
423           copied_elements++;
424         }
425       }
426     }
427     else
428     {
429       copied_elements = rd_count;
430       rd_selected = (struct GNUNET_NAMESTORE_RecordData *) rd;
431     }
432   }
433   else
434   {
435     /* No results */
436     copied_elements = 0;
437     rd_selected = NULL;
438     expire = GNUNET_TIME_UNIT_ZERO_ABS;
439   }
440
441   rd_ser_len = GNUNET_NAMESTORE_records_get_size(copied_elements, rd_selected);
442   char rd_ser[rd_ser_len];
443   GNUNET_NAMESTORE_records_serialize(copied_elements, rd_selected, rd_ser_len, rd_ser);
444
445   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found %u records for name `%s' in zone `%s'\n",
446       copied_elements, lnc->name, GNUNET_short_h2s(lnc->zone));
447
448   if ((copied_elements == rd_count) && (NULL != signature))
449     contains_signature = GNUNET_YES; /* returning all records, so include signature */
450   else
451     contains_signature = GNUNET_NO; /* returning not all records, so do not include signature */
452
453
454   if ((NULL != zone_key) && (copied_elements == rd_count))
455   {
456     GNUNET_CRYPTO_short_hash(zone_key, sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded), &zone_key_hash);
457     GNUNET_CRYPTO_short_hash_double (&zone_key_hash, &long_hash);
458     if (GNUNET_CONTAINER_multihashmap_contains(zonekeys, &long_hash))
459     {
460       cc = GNUNET_CONTAINER_multihashmap_get(zonekeys, &long_hash);
461       e = get_block_expiration_time(rd_count, rd);
462       signature_new = GNUNET_NAMESTORE_create_signature(cc->privkey, e, name, rd, rd_count);
463       GNUNET_assert (signature_new != NULL);
464       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating signature for name `%s' with %u records in zone `%s'\n",name, copied_elements, GNUNET_short_h2s(&zone_key_hash));
465       authoritative = GNUNET_YES;
466     }
467     else
468       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "I am not authoritative for name `%s' in zone `%s'\n",name, GNUNET_short_h2s(&zone_key_hash));
469   }
470
471   r_size = sizeof (struct LookupNameResponseMessage) +
472            sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
473            name_len +
474            rd_ser_len;
475
476   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message\n", "NAMESTORE_LOOKUP_NAME_RESPONSE");
477   lnr_msg = GNUNET_malloc (r_size);
478   lnr_msg->gns_header.header.type = ntohs (GNUNET_MESSAGE_TYPE_NAMESTORE_LOOKUP_NAME_RESPONSE);
479   lnr_msg->gns_header.header.size = ntohs (r_size);
480   lnr_msg->gns_header.r_id = htonl (lnc->request_id);
481   lnr_msg->rd_count = htons (copied_elements);
482   lnr_msg->rd_len = htons (rd_ser_len);
483   lnr_msg->name_len = htons (name_len);
484   lnr_msg->expire = GNUNET_TIME_absolute_hton(get_block_expiration_time(copied_elements, rd_selected));
485
486   if (rd_selected != rd)
487     GNUNET_free (rd_selected);
488
489   if (zone_key != NULL)
490     lnr_msg->public_key = (*zone_key);
491   else
492     memset(&lnr_msg->public_key, '\0', sizeof (lnr_msg->public_key));
493
494   if (GNUNET_YES == authoritative)
495   { /* use new created signature */
496     lnr_msg->contains_sig = htons (GNUNET_YES);
497     GNUNET_assert (signature_new != NULL);
498     lnr_msg->signature = *signature_new;
499     GNUNET_free (signature_new);
500   }
501   else if (GNUNET_YES == contains_signature)
502   {
503     /* use existing signature */
504     lnr_msg->contains_sig = htons (GNUNET_YES);
505     GNUNET_assert (signature != NULL);
506     lnr_msg->signature = *signature;
507   }
508   else
509   {
510     /* use no signature */
511     memset (&lnr_msg->signature, '\0', sizeof (lnr_msg->signature));
512   }
513
514   name_tmp = (char *) &lnr_msg[1];
515   rd_tmp = &name_tmp[name_len];
516
517   memcpy (name_tmp, name, name_len);
518   memcpy (rd_tmp, rd_ser, rd_ser_len);
519
520   GNUNET_SERVER_notification_context_unicast (snc, lnc->nc->client, (const struct GNUNET_MessageHeader *) lnr_msg, GNUNET_NO);
521   GNUNET_free (lnr_msg);
522 }
523
524 static void handle_lookup_name (void *cls,
525                           struct GNUNET_SERVER_Client * client,
526                           const struct GNUNET_MessageHeader * message)
527 {
528   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "NAMESTORE_LOOKUP_NAME");
529   struct LookupNameContext lnc;
530   struct GNUNET_NAMESTORE_Client *nc;
531   size_t name_len;
532   char * name;
533   uint32_t rid = 0;
534   uint32_t type = 0;
535
536   if (ntohs (message->size) < sizeof (struct LookupNameMessage))
537   {
538     GNUNET_break_op (0);
539     GNUNET_SERVER_receive_done (client, GNUNET_OK);
540     return;
541   }
542
543   nc = client_lookup(client);
544   if (nc == NULL)
545   {
546     GNUNET_break_op (0);
547     GNUNET_SERVER_receive_done (client, GNUNET_OK);
548     return;
549   }
550
551   struct LookupNameMessage * ln_msg = (struct LookupNameMessage *) message;
552   rid = ntohl (ln_msg->gns_header.r_id);
553   name_len = ntohl (ln_msg->name_len);
554   type = ntohl (ln_msg->record_type);
555
556   if ((name_len == 0) || (name_len > 256))
557   {
558     GNUNET_break_op (0);
559     GNUNET_SERVER_receive_done (client, GNUNET_OK);
560     return;
561   }
562
563   name = (char *) &ln_msg[1];
564   if (name[name_len -1] != '\0')
565   {
566     GNUNET_break_op (0);
567     GNUNET_SERVER_receive_done (client, GNUNET_OK);
568     return;
569   }
570
571   if (0 == type)
572     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Looking up all records for name `%s' in zone `%s'\n", name, GNUNET_short_h2s(&ln_msg->zone));
573   else
574     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Looking up records with type %u for name `%s' in zone `%s'\n", type, name, GNUNET_short_h2s(&ln_msg->zone));
575
576   /* do the actual lookup */
577   lnc.request_id = rid;
578   lnc.nc = nc;
579   lnc.record_type = type;
580   lnc.name = name;
581   lnc.zone = &ln_msg->zone;
582   GSN_database->iterate_records(GSN_database->cls, &ln_msg->zone, name, 0, &handle_lookup_name_it, &lnc);
583
584   GNUNET_SERVER_receive_done (client, GNUNET_OK);
585 }
586
587 static void handle_record_put (void *cls,
588                           struct GNUNET_SERVER_Client * client,
589                           const struct GNUNET_MessageHeader * message)
590 {
591   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "NAMESTORE_RECORD_PUT");
592   struct GNUNET_NAMESTORE_Client *nc;
593   struct GNUNET_TIME_Absolute expire;
594   struct GNUNET_CRYPTO_RsaSignature *signature;
595   struct RecordPutResponseMessage rpr_msg;
596   size_t name_len;
597   size_t msg_size;
598   size_t msg_size_exp;
599   char * name;
600   char * rd_ser;
601   uint32_t rid = 0;
602   uint32_t rd_ser_len;
603   uint32_t rd_count;
604   int res = GNUNET_SYSERR;
605
606   if (ntohs (message->size) < sizeof (struct RecordPutMessage))
607   {
608     GNUNET_break_op (0);
609     GNUNET_SERVER_receive_done (client, GNUNET_OK);
610     return;
611   }
612
613   nc = client_lookup (client);
614   if (nc == NULL)
615   {
616     GNUNET_break_op (0);
617     GNUNET_SERVER_receive_done (client, GNUNET_OK);
618     return;
619   }
620
621   struct RecordPutMessage * rp_msg = (struct RecordPutMessage *) message;
622
623   rid = ntohl (rp_msg->gns_header.r_id);
624   msg_size = ntohs (rp_msg->gns_header.header.size);
625   name_len = ntohs (rp_msg->name_len);
626   rd_count = ntohs (rp_msg->rd_count);
627   rd_ser_len = ntohs(rp_msg->rd_len);
628
629   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
630   {
631     GNUNET_break_op (0);
632     GNUNET_SERVER_receive_done (client, GNUNET_OK);
633     return;
634   }
635
636   if ((rd_count < 1) || (rd_ser_len < 1) || (name_len >=256) || (name_len == 0))
637   {
638     GNUNET_break_op (0);
639     GNUNET_SERVER_receive_done (client, GNUNET_OK);
640     return;
641   }
642
643   msg_size_exp = sizeof (struct RecordPutMessage) +  name_len  + rd_ser_len;
644   if (msg_size != msg_size_exp)
645   {
646     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Expected message %u size but message size is %u \n", msg_size_exp, msg_size);
647     GNUNET_break_op (0);
648     GNUNET_SERVER_receive_done (client, GNUNET_OK);
649     return;
650   }
651   if ((name_len == 0) || (name_len > 256))
652   {
653     GNUNET_break_op (0);
654     GNUNET_SERVER_receive_done (client, GNUNET_OK);
655     return;
656   }
657
658   name = (char *) &rp_msg[1];
659
660   if (name[name_len -1] != '\0')
661   {
662     GNUNET_break_op (0);
663     GNUNET_SERVER_receive_done (client, GNUNET_OK);
664     return;
665   }
666
667   expire = GNUNET_TIME_absolute_ntoh(rp_msg->expire);
668   signature = (struct GNUNET_CRYPTO_RsaSignature *) &rp_msg->signature;
669
670   rd_ser = &name[name_len];
671   struct GNUNET_NAMESTORE_RecordData rd[rd_count];
672   res = GNUNET_NAMESTORE_records_deserialize(rd_ser_len, rd_ser, rd_count, rd);
673   if (res != GNUNET_OK)
674   {
675     GNUNET_break_op (0);
676     goto send;
677   }
678
679   struct GNUNET_CRYPTO_ShortHashCode zone_hash;
680   GNUNET_CRYPTO_short_hash (&rp_msg->public_key, sizeof (rp_msg->public_key), &zone_hash);
681
682   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Putting %u record for name `%s' in zone `%s'\n", rd_count, name, GNUNET_short_h2s(&zone_hash));
683
684   /* Database operation */
685   res = GSN_database->put_records(GSN_database->cls,
686                                 &rp_msg->public_key,
687                                 expire,
688                                 name,
689                                 rd_count, rd,
690                                 signature);
691
692   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Putting record for name `%s': %s\n",
693       name, (res == GNUNET_OK) ? "OK" : "FAIL");
694
695   /* Send response */
696 send:
697   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message\n", "RECORD_PUT_RESPONSE");
698   rpr_msg.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_PUT_RESPONSE);
699   rpr_msg.gns_header.header.size = htons (sizeof (struct RecordPutResponseMessage));
700   rpr_msg.gns_header.r_id = htonl (rid);
701   rpr_msg.op_result = htonl (res);
702   GNUNET_SERVER_notification_context_unicast (snc, nc->client, (const struct GNUNET_MessageHeader *) &rpr_msg, GNUNET_NO);
703
704   GNUNET_SERVER_receive_done (client, GNUNET_OK);
705 }
706
707 struct CreateRecordContext
708 {
709   struct GNUNET_NAMESTORE_RecordData *rd;
710   struct GNUNET_CRYPTO_RsaPrivateKey *pkey;
711   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pubkey;
712   struct GNUNET_TIME_Absolute expire;
713   char *name;
714   int res;
715 };
716
717
718 static void
719 handle_create_record_it (void *cls,
720     const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pubkey,
721     struct GNUNET_TIME_Absolute expire,
722     const char *name,
723     unsigned int rd_count,
724     const struct GNUNET_NAMESTORE_RecordData *rd,
725     const struct GNUNET_CRYPTO_RsaSignature *signature)
726 {
727   struct CreateRecordContext * crc = cls;
728   struct GNUNET_NAMESTORE_RecordData *rd_new = NULL;
729   struct GNUNET_CRYPTO_RsaSignature dummy_signature;
730   struct GNUNET_TIME_Absolute block_expiration;
731   int res;
732   int exist = GNUNET_SYSERR;
733   int update = GNUNET_NO;
734   int c;
735   int rd_count_new = 0;
736
737   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found %u existing records for `%s'\n", rd_count, crc->name);
738   for (c = 0; c < rd_count; c++)
739   {
740     if ((crc->rd->record_type == GNUNET_NAMESTORE_TYPE_PKEY) && (rd[c].record_type == GNUNET_NAMESTORE_TYPE_PKEY))
741     {
742       /* Update unique PKEY */
743       exist = c;
744       update = GNUNET_YES;
745      break;
746     }
747     else if ((crc->rd->record_type == GNUNET_NAMESTORE_TYPE_PSEU) && (rd[c].record_type == GNUNET_NAMESTORE_TYPE_PSEU))
748     {
749       /* Update unique PSEU */
750       exist = c;
751       update = GNUNET_YES;
752      break;
753     }
754     else if ((crc->rd->record_type == rd[c].record_type) &&
755         (crc->rd->data_size == rd[c].data_size) &&
756         (0 == memcmp (crc->rd->data, rd[c].data, rd[c].data_size)))
757     {
758       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found existing records for `%s' to update expiration date!\n", crc->name);
759       exist = c;
760       if (crc->rd->expiration.abs_value != rd[c].expiration.abs_value)
761         update = GNUNET_YES;
762        break;
763     }
764   }
765
766   if (exist == GNUNET_SYSERR)
767     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "New record does not exist for name `%s'!\n", crc->name);
768
769   if (exist == GNUNET_SYSERR)
770   {
771     rd_new = GNUNET_malloc ((rd_count+1) * sizeof (struct GNUNET_NAMESTORE_RecordData));
772     memcpy (rd_new, rd, rd_count * sizeof (struct GNUNET_NAMESTORE_RecordData));
773     rd_count_new = rd_count + 1;
774     rd_new[rd_count] = *(crc->rd);
775   }
776   else if (update == GNUNET_NO)
777   {
778     /* Exact same record already exists */
779     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "No update for %s' record required!\n", crc->name);
780     res = GNUNET_NO;
781     goto end;
782   }
783   else if (update == GNUNET_YES)
784   {
785     /* Update record */
786     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Updating existing records for `%s'!\n", crc->name);
787     rd_new = GNUNET_malloc ((rd_count) * sizeof (struct GNUNET_NAMESTORE_RecordData));
788     memcpy (rd_new, rd, rd_count * sizeof (struct GNUNET_NAMESTORE_RecordData));
789     rd_count_new = rd_count;
790     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Updating expiration from %llu to %llu!\n", rd_new[exist].expiration.abs_value, crc->rd->expiration.abs_value);
791     rd_new[exist] = *(crc->rd);
792   }
793
794   block_expiration = GNUNET_TIME_absolute_max(crc->expire, expire);
795   if (block_expiration.abs_value != expire.abs_value)
796     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Updated block expiration time\n");
797
798   memset (&dummy_signature, '\0', sizeof (dummy_signature));
799
800   /* Database operation */
801   GNUNET_assert ((rd_new != NULL) && (rd_count_new > 0));
802   res = GSN_database->put_records(GSN_database->cls,
803                                 (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *) crc->pubkey,
804                                 block_expiration,
805                                 crc->name,
806                                 rd_count_new, rd_new,
807                                 &dummy_signature);
808   GNUNET_break (GNUNET_OK == res);
809   if (res == GNUNET_OK)
810     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Successfully put record for `%s' in database \n", crc->name);
811   else
812     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Failed to put record for `%s' in database \n", crc->name);
813   res = GNUNET_YES;
814
815 end:
816   GNUNET_free_non_null (rd_new);
817
818   switch (res) {
819     case GNUNET_SYSERR:
820        /* failed to create the record */
821        crc->res = GNUNET_SYSERR;
822       break;
823     case GNUNET_YES:
824       /* database operations OK */
825       if (GNUNET_YES == update)
826       {
827         /* we updated an existing record */
828         crc->res = GNUNET_NO;
829       }
830       else
831       {
832         /* we created a new record */
833         crc->res = GNUNET_YES;
834       }
835       break;
836     case GNUNET_NO:
837         /* identical entry existed, so we did nothing */
838       GNUNET_break(0);
839         crc->res = GNUNET_NO;
840       break;
841     default:
842       break;
843   }
844
845   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Update result for name `%s' %u\n", crc->name, res);
846
847 }
848
849 static void handle_record_create (void *cls,
850                           struct GNUNET_SERVER_Client * client,
851                           const struct GNUNET_MessageHeader * message)
852 {
853   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "NAMESTORE_RECORD_CREATE");
854   struct GNUNET_NAMESTORE_Client *nc;
855   struct GNUNET_NAMESTORE_CryptoContainer *cc;
856   struct CreateRecordContext crc;
857   struct GNUNET_CRYPTO_RsaPrivateKey *pkey;
858   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pub;
859   struct RecordCreateResponseMessage rcr_msg;
860   struct GNUNET_CRYPTO_ShortHashCode pubkey_hash;
861   GNUNET_HashCode long_hash;
862   size_t name_len;
863   size_t msg_size;
864   size_t msg_size_exp;
865   size_t rd_ser_len;
866   size_t key_len;
867   uint32_t rid = 0;
868   char *pkey_tmp;
869   char *name_tmp;
870   char *rd_ser;
871   int rd_count;
872
873   int res = GNUNET_SYSERR;
874   crc.res = GNUNET_SYSERR;
875
876   if (ntohs (message->size) < sizeof (struct RecordCreateMessage))
877   {
878     GNUNET_break_op (0);
879     GNUNET_SERVER_receive_done (client, GNUNET_OK);
880     return;
881   }
882
883   nc = client_lookup(client);
884   if (nc == NULL)
885   {
886     GNUNET_break_op (0);
887     GNUNET_SERVER_receive_done (client, GNUNET_OK);
888     return;
889   }
890
891   struct RecordCreateMessage * rp_msg = (struct RecordCreateMessage *) message;
892   rid = ntohl (rp_msg->gns_header.r_id);
893   name_len = ntohs (rp_msg->name_len);
894   msg_size = ntohs (message->size);
895   rd_count = ntohs (rp_msg->rd_count);
896   rd_ser_len = ntohs (rp_msg->rd_len);
897   key_len = ntohs (rp_msg->pkey_len);
898   msg_size_exp = sizeof (struct RecordCreateMessage) + key_len + name_len + rd_ser_len;
899
900   if (msg_size != msg_size_exp)
901   {
902     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Expected message %u size but message size is %u \n", msg_size_exp, msg_size);
903     GNUNET_break_op (0);
904     GNUNET_SERVER_receive_done (client, GNUNET_OK);
905     return;
906   }
907
908   if ((name_len == 0) || (name_len > 256))
909   {
910     GNUNET_break_op (0);
911     GNUNET_SERVER_receive_done (client, GNUNET_OK);
912     return;
913   }
914
915   pkey_tmp = (char *) &rp_msg[1];
916   name_tmp = &pkey_tmp[key_len];
917   rd_ser = &name_tmp[name_len];
918
919   if (name_tmp[name_len -1] != '\0')
920   {
921     GNUNET_break_op (0);
922     GNUNET_SERVER_receive_done (client, GNUNET_OK);
923     return;
924   }
925
926   struct GNUNET_NAMESTORE_RecordData rd[rd_count];
927
928   res = GNUNET_NAMESTORE_records_deserialize(rd_ser_len, rd_ser, rd_count, rd);
929   if ((res != GNUNET_OK) || (rd_count != 1))
930   {
931     GNUNET_break_op (0);
932     goto send;
933   }
934   /* Extracting and converting private key */
935   pkey = GNUNET_CRYPTO_rsa_decode_key((char *) pkey_tmp, key_len);
936   GNUNET_assert (pkey != NULL);
937   GNUNET_CRYPTO_rsa_key_get_public(pkey, &pub);
938   GNUNET_CRYPTO_short_hash (&pub, sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded), &pubkey_hash);
939   GNUNET_CRYPTO_short_hash_double (&pubkey_hash, &long_hash);
940
941   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(zonekeys, &long_hash))
942   {
943     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received new private key for zone `%s'\n",GNUNET_short_h2s(&pubkey_hash));
944
945     cc = GNUNET_malloc (sizeof (struct GNUNET_NAMESTORE_CryptoContainer));
946     cc->privkey = GNUNET_CRYPTO_rsa_decode_key((char *) pkey_tmp, key_len);
947     cc->pubkey = GNUNET_malloc(sizeof (pub));
948     memcpy (cc->pubkey, &pub, sizeof(pub));
949     cc->zone = pubkey_hash;
950     GNUNET_CONTAINER_multihashmap_put(zonekeys, &long_hash, cc, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
951   }
952
953   crc.expire = GNUNET_TIME_absolute_ntoh(rp_msg->expire);
954   crc.res = GNUNET_SYSERR;
955   crc.pkey = pkey;
956   crc.pubkey = &pub;
957   crc.rd = rd;
958   crc.name = name_tmp;
959
960   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating record for name `%s' in zone `%s'\n", name_tmp, GNUNET_short_h2s(&pubkey_hash));
961
962   /* Get existing records for name */
963   res = GSN_database->iterate_records(GSN_database->cls, &pubkey_hash, name_tmp, 0, &handle_create_record_it, &crc);
964   if (res != GNUNET_SYSERR)
965     res = GNUNET_OK;
966   GNUNET_CRYPTO_rsa_key_free(pkey);
967   pkey = NULL;
968
969   /* Send response */
970 send:
971   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message\n", "RECORD_CREATE_RESPONSE");
972   rcr_msg.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_CREATE_RESPONSE);
973   rcr_msg.gns_header.header.size = htons (sizeof (struct RecordCreateResponseMessage));
974   rcr_msg.gns_header.r_id = htonl (rid);
975   if ((GNUNET_OK == res) && (crc.res == GNUNET_YES))
976     rcr_msg.op_result = htonl (GNUNET_YES);
977   else if ((GNUNET_OK == res) && (crc.res == GNUNET_NO))
978     rcr_msg.op_result = htonl (GNUNET_NO);
979   else
980     rcr_msg.op_result = htonl (GNUNET_SYSERR);
981   GNUNET_SERVER_notification_context_unicast (snc, nc->client, (const struct GNUNET_MessageHeader *) &rcr_msg, GNUNET_NO);
982
983   GNUNET_SERVER_receive_done (client, GNUNET_OK);
984 }
985
986
987 struct RemoveRecordContext
988 {
989   struct GNUNET_NAMESTORE_RecordData *rd;
990   struct GNUNET_CRYPTO_RsaPrivateKey *pkey;
991   int remove_name;
992   uint16_t op_res;
993 };
994
995 static void
996 handle_record_remove_it (void *cls,
997     const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
998     struct GNUNET_TIME_Absolute expire,
999     const char *name,
1000     unsigned int rd_count,
1001     const struct GNUNET_NAMESTORE_RecordData *rd,
1002     const struct GNUNET_CRYPTO_RsaSignature *signature)
1003 {
1004   struct RemoveRecordContext *rrc = cls;
1005   unsigned int c;
1006   int res;
1007   int found;
1008   unsigned int rd_count_new;
1009
1010   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Name `%s 'currently has %u records\n", name, rd_count);
1011
1012   if (rd_count == 0)
1013   {
1014     /* Could not find record to remove */
1015     rrc->op_res = 1;
1016     return;
1017   }
1018
1019   /* Find record to remove */
1020   found = GNUNET_SYSERR;
1021   for (c = 0; c < rd_count; c++)
1022   {
1023     GNUNET_break(0);
1024     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "SENT FLAGES: %u \n",rd[c].flags);
1025     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "STORED FLAGES: %u \n",rrc->rd->flags);
1026     /*
1027     if (rd[c].flags != rrc->rd->flags)
1028        continue;*/
1029     GNUNET_break(0);
1030     if (rd[c].record_type != rrc->rd->record_type)
1031        continue;
1032     GNUNET_break(0);
1033     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "SENT FLAGES: %u \n",rd[c].data_size);
1034     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "STORED FLAGES: %u \n",rrc->rd->data_size);
1035     /*
1036     if (rd[c].data_size != rrc->rd->data_size)
1037        continue;
1038     GNUNET_break(0);
1039     if (0 != memcmp (rd[c].data, rrc->rd->data, rrc->rd->data_size))
1040         continue;
1041     GNUNET_break(0); */
1042     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found record to remove!\n", rd_count);
1043     found = c;
1044     break;
1045   }
1046   if (GNUNET_SYSERR == found)
1047   {
1048     /* Could not find record to remove */
1049     rrc->op_res = 2;
1050     return;
1051   }
1052
1053   if (rd_count-1 == 0)
1054   {
1055     struct GNUNET_CRYPTO_ShortHashCode pubkey_hash;
1056     GNUNET_CRYPTO_short_hash (zone_key, sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded), &pubkey_hash);
1057     res = GSN_database->remove_records (GSN_database->cls,
1058                                         &pubkey_hash,
1059                                         name);
1060     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1061                 "No records left for name `%s', removing name\n",
1062                 name, res);
1063     if (GNUNET_OK != res)
1064     {
1065       /* Could put records into database */
1066       rrc->op_res = 4;
1067       return;
1068     }
1069     rrc->op_res = 0;
1070     return;
1071   }
1072
1073   rd_count_new = rd_count -1;
1074   struct GNUNET_NAMESTORE_RecordData rd_new[rd_count_new];
1075
1076   unsigned int c2 = 0;
1077   for (c = 0; c < rd_count; c++)
1078   {
1079     if (c != found)
1080     {
1081       GNUNET_assert (c2 < rd_count_new);
1082       rd_new[c2] = rd[c];
1083       c2++;
1084     }
1085   }
1086
1087   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Name `%s' now has %u records\n", name, rd_count_new);
1088
1089   /* Create dummy signature */
1090   struct GNUNET_CRYPTO_RsaSignature dummy_signature;
1091   memset (&dummy_signature, '\0', sizeof (dummy_signature));
1092
1093
1094   /* Put records */
1095   res = GSN_database->put_records(GSN_database->cls,
1096                                   zone_key,
1097                                   expire,
1098                                   name,
1099                                   rd_count_new, rd_new,
1100                                   &dummy_signature);
1101   if (GNUNET_OK != res)
1102   {
1103     /* Could put records into database */
1104     rrc->op_res = 4;
1105     return;
1106   }
1107
1108   rrc->op_res = 0;
1109 }
1110
1111 static void handle_record_remove (void *cls,
1112                           struct GNUNET_SERVER_Client * client,
1113                           const struct GNUNET_MessageHeader * message)
1114 {
1115   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "NAMESTORE_RECORD_REMOVE");
1116   struct GNUNET_NAMESTORE_Client *nc;
1117   struct RecordRemoveResponseMessage rrr_msg;
1118   struct GNUNET_CRYPTO_RsaPrivateKey *pkey;
1119   struct GNUNET_NAMESTORE_CryptoContainer *cc = NULL;
1120   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pub;
1121   struct GNUNET_CRYPTO_ShortHashCode pubkey_hash;
1122   GNUNET_HashCode long_hash;
1123   char * pkey_tmp = NULL;
1124   char * name_tmp = NULL;
1125   char * rd_ser = NULL;
1126   size_t key_len = 0;
1127   size_t name_len = 0;
1128   size_t rd_ser_len = 0;
1129   size_t msg_size = 0;
1130   size_t msg_size_exp = 0;
1131   uint32_t rd_count;
1132   uint32_t rid = 0;
1133
1134   int res = GNUNET_SYSERR;
1135
1136   if (ntohs (message->size) < sizeof (struct RecordRemoveMessage))
1137   {
1138     GNUNET_break_op (0);
1139     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1140     return;
1141   }
1142
1143   nc = client_lookup(client);
1144   if (nc == NULL)
1145   {
1146     GNUNET_break_op (0);
1147     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1148     return;
1149   }
1150
1151   struct RecordRemoveMessage * rr_msg = (struct RecordRemoveMessage *) message;
1152   rid = ntohl (rr_msg->gns_header.r_id);
1153   name_len = ntohs (rr_msg->name_len);
1154   rd_ser_len = ntohs (rr_msg->rd_len);
1155   rd_count = ntohs (rr_msg->rd_count);
1156   key_len = ntohs (rr_msg->pkey_len);
1157   msg_size = ntohs (message->size);
1158
1159   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
1160   {
1161     GNUNET_break_op (0);
1162     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1163     return;
1164   }
1165
1166   if ((name_len >=256) || (name_len == 0))
1167   {
1168     GNUNET_break_op (0);
1169     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1170     return;
1171   }
1172
1173   msg_size_exp = sizeof (struct RecordRemoveMessage) + key_len + name_len + rd_ser_len;
1174   if (msg_size != msg_size_exp)
1175   {
1176     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Expected message %u size but message size is %u \n", msg_size_exp, msg_size);
1177     GNUNET_break_op (0);
1178     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1179     return;
1180   }
1181
1182   pkey_tmp = (char *) &rr_msg[1];
1183   name_tmp = &pkey_tmp[key_len];
1184   rd_ser = &name_tmp[name_len];
1185
1186
1187   if ((name_len == 0) || (name_len > 256))
1188   {
1189     GNUNET_break_op (0);
1190     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1191     return;
1192   }
1193
1194   if (name_tmp[name_len -1] != '\0')
1195   {
1196     GNUNET_break_op (0);
1197     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1198     return;
1199   }
1200
1201   /* Extracting and converting private key */
1202   pkey = GNUNET_CRYPTO_rsa_decode_key((char *) pkey_tmp, key_len);
1203   GNUNET_assert (pkey != NULL);
1204   GNUNET_CRYPTO_rsa_key_get_public(pkey, &pub);
1205   GNUNET_CRYPTO_short_hash (&pub, sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded), &pubkey_hash);
1206   GNUNET_CRYPTO_short_hash_double (&pubkey_hash, &long_hash);
1207
1208   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(zonekeys, &long_hash))
1209   {
1210     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received new private key for zone `%s'\n",GNUNET_short_h2s(&pubkey_hash));
1211     cc = GNUNET_malloc (sizeof (struct GNUNET_NAMESTORE_CryptoContainer));
1212     cc->privkey = GNUNET_CRYPTO_rsa_decode_key((char *) pkey_tmp, key_len);
1213     cc->pubkey = GNUNET_malloc(sizeof (pub));
1214     memcpy (cc->pubkey, &pub, sizeof(pub));
1215     cc->zone = pubkey_hash;
1216
1217     GNUNET_CONTAINER_multihashmap_put(zonekeys, &long_hash, cc, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1218   }
1219
1220
1221   struct GNUNET_NAMESTORE_RecordData rd[rd_count];
1222   res = GNUNET_NAMESTORE_records_deserialize(rd_ser_len, rd_ser, rd_count, rd);
1223   if ((res != GNUNET_OK) || (rd_count > 1))
1224   {
1225     GNUNET_break_op (0);
1226     goto send;
1227   }
1228
1229   if (0 == rd_count)
1230   {
1231     /* remove the whole name and all records */
1232     /* Database operation */
1233     res = GSN_database->remove_records (GSN_database->cls,
1234                                          &pubkey_hash,
1235                                          name_tmp);
1236     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Removing name `%s': %s\n",
1237         name_tmp, (GNUNET_OK == res) ? "OK" : "FAIL");
1238
1239     if (GNUNET_OK != res)
1240       /* Could not remove entry from database */
1241       res = 4;
1242     else
1243       res = 0;
1244   }
1245   else
1246   {
1247     /* remove a single record */
1248     struct RemoveRecordContext rrc;
1249     rrc.rd = rd;
1250     rrc.pkey = pkey;
1251
1252     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Removing record for name `%s' in zone `%s'\n", name_tmp, GNUNET_short_h2s(&pubkey_hash));
1253
1254     /* Database operation */
1255     res = GSN_database->iterate_records (GSN_database->cls,
1256                                          &pubkey_hash,
1257                                          name_tmp,
1258                                          0,
1259                                          handle_record_remove_it, &rrc);
1260
1261     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Removing record for name `%s': %s\n",
1262         name_tmp, (rrc.op_res == 0) ? "OK" : "FAIL");
1263     res = rrc.op_res;
1264   }
1265   /* Send response */
1266 send:
1267   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message\n", "RECORD_REMOVE_RESPONSE");
1268   rrr_msg.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_REMOVE_RESPONSE);
1269   rrr_msg.gns_header.header.size = htons (sizeof (struct RecordRemoveResponseMessage));
1270   rrr_msg.gns_header.r_id = htonl (rid);
1271   rrr_msg.op_result = htonl (res);
1272   GNUNET_SERVER_notification_context_unicast (snc, nc->client, (const struct GNUNET_MessageHeader *) &rrr_msg, GNUNET_NO);
1273
1274   GNUNET_CRYPTO_rsa_key_free (pkey);
1275
1276   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1277 }
1278
1279
1280 struct ZoneToNameCtx
1281 {
1282   struct GNUNET_NAMESTORE_Client *nc;
1283   uint32_t rid;
1284 };
1285
1286 static void
1287 handle_zone_to_name_it (void *cls,
1288     const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
1289     struct GNUNET_TIME_Absolute expire,
1290     const char *name,
1291     unsigned int rd_count,
1292     const struct GNUNET_NAMESTORE_RecordData *rd,
1293     const struct GNUNET_CRYPTO_RsaSignature *signature)
1294 {
1295   struct ZoneToNameCtx * ztn_ctx = cls;
1296   struct ZoneToNameResponseMessage *ztnr_msg;
1297   int16_t res = GNUNET_SYSERR;
1298   uint16_t name_len = 0;
1299   uint16_t rd_ser_len = 0 ;
1300   int32_t contains_sig = 0;
1301   size_t msg_size = 0;
1302
1303   char *rd_ser = NULL;
1304   char *name_tmp;
1305   char *rd_tmp;
1306   char *sig_tmp;
1307
1308   if ((zone_key != NULL) && (name != NULL))
1309   {
1310     /* found result */
1311     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found results: name is `%s', has %u records\n", name, rd_count);
1312     res = GNUNET_YES;
1313     name_len = strlen (name) +1;
1314   }
1315   else
1316   {
1317     /* no result found */
1318     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found no results\n");
1319     res = GNUNET_NO;
1320     name_len = 0;
1321   }
1322
1323   if (rd_count > 0)
1324   {
1325     rd_ser_len = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
1326     rd_ser = GNUNET_malloc (rd_ser_len);
1327     GNUNET_NAMESTORE_records_serialize(rd_count, rd, rd_ser_len, rd_ser);
1328   }
1329   else
1330     rd_ser_len = 0;
1331
1332   if (signature != NULL)
1333     contains_sig = GNUNET_YES;
1334   else
1335     contains_sig = GNUNET_NO;
1336
1337
1338
1339   msg_size = sizeof (struct ZoneToNameResponseMessage) + name_len + rd_ser_len + contains_sig * sizeof (struct GNUNET_CRYPTO_RsaSignature);
1340   ztnr_msg = GNUNET_malloc (msg_size);
1341
1342   name_tmp = (char *) &ztnr_msg[1];
1343   rd_tmp = &name_tmp[name_len];
1344   sig_tmp = &rd_tmp[rd_ser_len];
1345
1346   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message\n", "ZONE_TO_NAME_RESPONSE");
1347   ztnr_msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME_RESPONSE);
1348   ztnr_msg->gns_header.header.size = htons (msg_size);
1349   ztnr_msg->gns_header.r_id = htonl (ztn_ctx->rid);
1350   ztnr_msg->res = htons (res);
1351   ztnr_msg->rd_len = htons (rd_ser_len);
1352   ztnr_msg->rd_count = htons (rd_count);
1353   ztnr_msg->name_len = htons (name_len);
1354   ztnr_msg->expire = GNUNET_TIME_absolute_hton(expire);
1355   if (zone_key != NULL)
1356     ztnr_msg->zone_key = *zone_key;
1357   else
1358     memset (&ztnr_msg->zone_key, '\0', sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1359
1360   if ((name_len > 0) && (name != NULL))
1361     memcpy (name_tmp, name, name_len);
1362
1363   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Name is `%s', has %u records, rd ser len %u msg_size %u\n", name, rd_count, rd_ser_len, msg_size);
1364   if ((rd_ser_len > 0) && (rd_ser != NULL))
1365     memcpy (rd_tmp, rd_ser, rd_ser_len);
1366   if ((GNUNET_YES == contains_sig) && (signature != NULL))
1367     memcpy (sig_tmp, signature, contains_sig * sizeof (struct GNUNET_CRYPTO_RsaSignature));
1368
1369   GNUNET_SERVER_notification_context_unicast (snc, ztn_ctx->nc->client, (const struct GNUNET_MessageHeader *) ztnr_msg, GNUNET_NO);
1370   GNUNET_free (ztnr_msg);
1371   GNUNET_free_non_null (rd_ser);
1372 }
1373
1374
1375 static void handle_zone_to_name (void *cls,
1376                           struct GNUNET_SERVER_Client * client,
1377                           const struct GNUNET_MessageHeader * message)
1378 {
1379   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "ZONE_TO_NAME");
1380   struct GNUNET_NAMESTORE_Client *nc;
1381   struct ZoneToNameCtx ztn_ctx;
1382   size_t msg_size = 0;
1383   uint32_t rid = 0;
1384
1385   if (ntohs (message->size) != sizeof (struct ZoneToNameMessage))
1386   {
1387     GNUNET_break_op (0);
1388     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1389     return;
1390   }
1391
1392   nc = client_lookup(client);
1393   if (nc == NULL)
1394   {
1395     GNUNET_break_op (0);
1396     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1397     return;
1398   }
1399
1400   struct ZoneToNameMessage *ztn_msg = (struct ZoneToNameMessage *) message;
1401
1402   if (msg_size > GNUNET_SERVER_MAX_MESSAGE_SIZE)
1403   {
1404     GNUNET_break_op (0);
1405     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1406     return;
1407   }
1408
1409   rid = ntohl (ztn_msg->gns_header.r_id);
1410
1411   ztn_ctx.rid = rid;
1412   ztn_ctx.nc = nc;
1413
1414   struct GNUNET_CRYPTO_ShortHashAsciiEncoded z_tmp;
1415   GNUNET_CRYPTO_short_hash_to_enc(&ztn_msg->zone, &z_tmp);
1416   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Looking up name for zone `%s' in zone `%s'\n",
1417       (char *) &z_tmp,
1418       GNUNET_short_h2s (&ztn_msg->value_zone));
1419
1420   GSN_database->zone_to_name (GSN_database->cls, &ztn_msg->zone, &ztn_msg->value_zone, &handle_zone_to_name_it, &ztn_ctx);
1421
1422   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1423 }
1424
1425 struct ZoneIterationProcResult
1426 {
1427   int have_zone_key;
1428   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded zone_key;
1429
1430   int have_signature;
1431   struct GNUNET_CRYPTO_RsaSignature signature;
1432   struct GNUNET_TIME_Absolute expire;
1433
1434   int have_name;
1435   char name[256];
1436
1437   size_t rd_ser_len;
1438   char *rd_ser;
1439 };
1440
1441
1442 void zone_iteration_proc (void *cls,
1443                          const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *zone_key,
1444                          struct GNUNET_TIME_Absolute expire,
1445                          const char *name,
1446                          unsigned int rd_count,
1447                          const struct GNUNET_NAMESTORE_RecordData *rd,
1448                          const struct GNUNET_CRYPTO_RsaSignature *signature)
1449 {
1450   struct GNUNET_NAMESTORE_ZoneIteration *zi = cls;
1451   struct GNUNET_NAMESTORE_Client *nc = zi->client;
1452   struct GNUNET_NAMESTORE_CryptoContainer * cc;
1453   struct GNUNET_CRYPTO_RsaSignature *signature_new = NULL;
1454   struct GNUNET_TIME_Absolute e;
1455   struct GNUNET_CRYPTO_ShortHashCode zone_key_hash;
1456   GNUNET_HashCode long_hash;
1457   int authoritative = GNUNET_NO;
1458
1459   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ZONE RESULT `%s'\n", name);
1460
1461   if ((zone_key == NULL) && (name == NULL))
1462   {
1463     struct ZoneIterationResponseMessage zir_msg;
1464     if (zi->has_zone == GNUNET_YES)
1465       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "No more results for zone `%s'\n", GNUNET_short_h2s(&zi->zone));
1466     else
1467       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "No more results for all zones\n");
1468
1469     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending empty `%s' message\n", "ZONE_ITERATION_RESPONSE");
1470     zir_msg.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_RESPONSE);
1471     zir_msg.gns_header.header.size = htons (sizeof (struct ZoneIterationResponseMessage));
1472     zir_msg.gns_header.r_id = htonl(zi->request_id);
1473     zir_msg.expire = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_zero());
1474     zir_msg.name_len = htons (0);
1475     zir_msg.reserved = htons (0);
1476     zir_msg.rd_count = htons (0);
1477     zir_msg.rd_len = htons (0);
1478     memset (&zir_msg.public_key, '\0', sizeof (zir_msg.public_key));
1479     memset (&zir_msg.signature, '\0', sizeof (zir_msg.signature));
1480     GNUNET_SERVER_notification_context_unicast (snc, nc->client, (const struct GNUNET_MessageHeader *) &zir_msg, GNUNET_NO);
1481
1482     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Removing zone iterator\n");
1483     GNUNET_CONTAINER_DLL_remove (nc->op_head, nc->op_tail, zi);
1484     GNUNET_free (zi);
1485     return;
1486   }
1487   else
1488   {
1489     struct ZoneIterationResponseMessage *zir_msg;
1490     if (zi->has_zone == GNUNET_YES)
1491       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending name `%s' for iteration over zone `%s'\n",
1492           name, GNUNET_short_h2s(&zi->zone));
1493     if (zi->has_zone == GNUNET_NO)
1494       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending name `%s' for iteration over all zones\n",
1495           name);
1496
1497     size_t name_len;
1498     size_t rd_ser_len;
1499     size_t msg_size;
1500     char *name_tmp;
1501     char *rd_tmp;
1502     name_len = strlen (name) +1;
1503
1504     rd_ser_len = GNUNET_NAMESTORE_records_get_size(rd_count, rd);
1505     char rd_ser[rd_ser_len];
1506     GNUNET_NAMESTORE_records_serialize(rd_count, rd, rd_ser_len, rd_ser);
1507     msg_size = sizeof (struct ZoneIterationResponseMessage) + name_len + rd_ser_len;
1508     zir_msg = GNUNET_malloc(msg_size);
1509
1510     name_tmp = (char *) &zir_msg[1];
1511     rd_tmp = &name_tmp[name_len];
1512
1513     GNUNET_CRYPTO_short_hash(zone_key, sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded), &zone_key_hash);
1514     GNUNET_CRYPTO_short_hash_double(&zone_key_hash, &long_hash);
1515     if (GNUNET_CONTAINER_multihashmap_contains(zonekeys, &long_hash))
1516     {
1517       cc = GNUNET_CONTAINER_multihashmap_get(zonekeys, &long_hash);
1518       e = get_block_expiration_time(rd_count, rd);
1519       expire = e;
1520       signature_new = GNUNET_NAMESTORE_create_signature(cc->privkey, e, name, rd, rd_count);
1521       GNUNET_assert (signature_new != NULL);
1522       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating signature for `%s' in zone `%s' with %u records  and expiration %llu\n", name, GNUNET_short_h2s(&zone_key_hash), rd_count, e.abs_value);
1523       authoritative = GNUNET_YES;
1524     }
1525
1526     zir_msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_RESPONSE);
1527     zir_msg->gns_header.header.size = htons (msg_size);
1528     zir_msg->gns_header.r_id = htonl(zi->request_id);
1529     zir_msg->expire = GNUNET_TIME_absolute_hton(expire);
1530     zir_msg->reserved = htons (0);
1531     zir_msg->name_len = htons (name_len);
1532     zir_msg->rd_count = htons (rd_count);
1533     zir_msg->rd_len = htons (rd_ser_len);
1534     if ((GNUNET_YES == authoritative) && (NULL != signature_new))
1535     {
1536       zir_msg->signature = *signature_new;
1537       GNUNET_free (signature_new);
1538     }
1539     else
1540       zir_msg->signature = *signature;
1541     GNUNET_assert (NULL != zone_key);
1542     if (zone_key != NULL)
1543       zir_msg->public_key = *zone_key;
1544     memcpy (name_tmp, name, name_len);
1545     memcpy (rd_tmp, rd_ser, rd_ser_len);
1546
1547     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending `%s' message with size %u\n", "ZONE_ITERATION_RESPONSE", msg_size);
1548     GNUNET_SERVER_notification_context_unicast (snc, nc->client, (const struct GNUNET_MessageHeader *) zir_msg, GNUNET_NO);
1549     GNUNET_free (zir_msg);
1550   }
1551 }
1552
1553 static void handle_iteration_start (void *cls,
1554                           struct GNUNET_SERVER_Client * client,
1555                           const struct GNUNET_MessageHeader * message)
1556 {
1557   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "ZONE_ITERATION_START");
1558
1559   struct ZoneIterationStartMessage * zis_msg = (struct ZoneIterationStartMessage *) message;
1560   struct GNUNET_NAMESTORE_Client *nc;
1561   struct GNUNET_NAMESTORE_ZoneIteration *zi;
1562
1563   nc = client_lookup(client);
1564   if (nc == NULL)
1565   {
1566     GNUNET_break_op (0);
1567     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1568     return;
1569   }
1570
1571   zi = GNUNET_malloc (sizeof (struct GNUNET_NAMESTORE_ZoneIteration));
1572   zi->request_id = ntohl (zis_msg->gns_header.r_id);
1573   zi->offset = 0;
1574   zi->client = nc;
1575   zi->zone = zis_msg->zone;
1576
1577   struct GNUNET_CRYPTO_ShortHashCode dummy;
1578   struct GNUNET_CRYPTO_ShortHashCode *zone_tmp;
1579   memset (&dummy, '\0', sizeof (dummy));
1580   if (0 == memcmp (&dummy, &zis_msg->zone, sizeof (dummy)))
1581   {
1582     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting to iterate over all zones\n");
1583     zi->has_zone = GNUNET_NO;
1584     zone_tmp = NULL;
1585   }
1586   else
1587   {
1588     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting to iterate over zone  `%s'\n", GNUNET_short_h2s (&zis_msg->zone));
1589     zi->has_zone = GNUNET_YES;
1590     zone_tmp = &zis_msg->zone;
1591   }
1592
1593   GNUNET_CONTAINER_DLL_insert (nc->op_head, nc->op_tail, zi);
1594
1595   GSN_database->iterate_records (GSN_database->cls, zone_tmp , NULL, zi->offset , &zone_iteration_proc, zi);
1596   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1597 }
1598
1599 static void handle_iteration_stop (void *cls,
1600                           struct GNUNET_SERVER_Client * client,
1601                           const struct GNUNET_MessageHeader * message)
1602 {
1603   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "ZONE_ITERATION_STOP");
1604
1605   struct GNUNET_NAMESTORE_Client *nc;
1606   struct GNUNET_NAMESTORE_ZoneIteration *zi;
1607   struct ZoneIterationStopMessage * zis_msg = (struct ZoneIterationStopMessage *) message;
1608   uint32_t rid;
1609
1610   nc = client_lookup(client);
1611   if (nc == NULL)
1612   {
1613     GNUNET_break_op (0);
1614     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1615     return;
1616   }
1617
1618   rid = ntohl (zis_msg->gns_header.r_id);
1619   for (zi = nc->op_head; zi != NULL; zi = zi->next)
1620   {
1621     if (zi->request_id == rid)
1622       break;
1623   }
1624   if (zi == NULL)
1625   {
1626     GNUNET_break_op (0);
1627     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1628     return;
1629   }
1630
1631   GNUNET_CONTAINER_DLL_remove(nc->op_head, nc->op_tail, zi);
1632   if (GNUNET_YES == zi->has_zone)
1633     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Stopped zone iteration for zone `%s'\n", GNUNET_short_h2s (&zi->zone));
1634   else
1635     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Stopped zone iteration all zones\n");
1636   GNUNET_free (zi);
1637
1638   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1639 }
1640
1641 static void handle_iteration_next (void *cls,
1642                           struct GNUNET_SERVER_Client * client,
1643                           const struct GNUNET_MessageHeader * message)
1644 {
1645   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "ZONE_ITERATION_NEXT");
1646
1647   struct GNUNET_NAMESTORE_Client *nc;
1648   struct GNUNET_NAMESTORE_ZoneIteration *zi;
1649   struct GNUNET_CRYPTO_ShortHashCode *zone_tmp;
1650   struct ZoneIterationStopMessage * zis_msg = (struct ZoneIterationStopMessage *) message;
1651   uint32_t rid;
1652
1653   nc = client_lookup(client);
1654   if (nc == NULL)
1655   {
1656     GNUNET_break_op (0);
1657     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1658     return;
1659   }
1660
1661   rid = ntohl (zis_msg->gns_header.r_id);
1662   for (zi = nc->op_head; zi != NULL; zi = zi->next)
1663   {
1664     if (zi->request_id == rid)
1665       break;
1666   }
1667   if (zi == NULL)
1668   {
1669     GNUNET_break_op (0);
1670     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1671     return;
1672   }
1673
1674   if (GNUNET_YES == zi->has_zone)
1675     zone_tmp = &zi->zone;
1676   else
1677     zone_tmp = NULL;
1678
1679   zi->offset++;
1680   GSN_database->iterate_records (GSN_database->cls, zone_tmp, NULL, zi->offset , &zone_iteration_proc, zi);
1681   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1682 }
1683
1684 int zonekey_file_it (void *cls, const char *filename)
1685 {
1686   GNUNET_HashCode long_hash;
1687   int *counter = cls;
1688    if ((filename != NULL) && (NULL != strstr(filename, ".zkey")))
1689    {
1690      struct GNUNET_CRYPTO_RsaPrivateKey * privkey;
1691      struct GNUNET_NAMESTORE_CryptoContainer *c;
1692      privkey = GNUNET_CRYPTO_rsa_key_create_from_file(filename);
1693      if (privkey == NULL)
1694        return GNUNET_OK;
1695
1696      c = GNUNET_malloc (sizeof (struct GNUNET_NAMESTORE_CryptoContainer));
1697      c->pubkey = GNUNET_malloc(sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
1698      c->privkey = privkey;
1699      GNUNET_CRYPTO_rsa_key_get_public(privkey, c->pubkey);
1700      GNUNET_CRYPTO_short_hash(c->pubkey, sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded), &c->zone);
1701
1702      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found zonefile for zone `%s'\n", GNUNET_short_h2s (&c->zone));
1703      GNUNET_CRYPTO_short_hash_double (&c->zone, &long_hash);
1704      GNUNET_CONTAINER_multihashmap_put(zonekeys, &long_hash, c, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1705      (*counter) ++;
1706    }
1707    return GNUNET_OK;
1708 }
1709
1710
1711 /**
1712  * Process template requests.
1713  *
1714  * @param cls closure
1715  * @param server the initialized server
1716  * @param cfg configuration to use
1717  */
1718 static void
1719 run (void *cls, struct GNUNET_SERVER_Handle *server,
1720      const struct GNUNET_CONFIGURATION_Handle *cfg)
1721 {
1722   char * database;
1723   int counter = 0;
1724   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting namestore service\n");
1725
1726   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1727     {&handle_start, NULL,
1728      GNUNET_MESSAGE_TYPE_NAMESTORE_START, sizeof (struct StartMessage)},
1729     {&handle_lookup_name, NULL,
1730      GNUNET_MESSAGE_TYPE_NAMESTORE_LOOKUP_NAME, 0},
1731     {&handle_record_put, NULL,
1732     GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_PUT, 0},
1733     {&handle_record_create, NULL,
1734      GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_CREATE, 0},
1735     {&handle_record_remove, NULL,
1736      GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_REMOVE, 0},
1737     {&handle_zone_to_name, NULL,
1738       GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME, 0},
1739     {&handle_iteration_start, NULL,
1740      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_START, sizeof (struct ZoneIterationStartMessage)},
1741     {&handle_iteration_next, NULL,
1742      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_NEXT, 0},
1743      {&handle_iteration_stop, NULL,
1744       GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_STOP, 0},
1745     {NULL, NULL, 0, 0}
1746   };
1747
1748   GSN_cfg = cfg;
1749
1750   /* Load private keys from disk */
1751   if (GNUNET_OK !=
1752       GNUNET_CONFIGURATION_get_value_filename (cfg, "namestore", "zonefile_directory",
1753                                              &zonefile_directory))
1754   {
1755     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("No directory to load zonefiles specified in configuration\n"));
1756     GNUNET_SCHEDULER_add_now (&cleanup_task, NULL);
1757     return;
1758   }
1759
1760   if (GNUNET_NO == GNUNET_DISK_file_test (zonefile_directory))
1761   {
1762     if (GNUNET_SYSERR == GNUNET_DISK_directory_create (zonefile_directory))
1763     {
1764       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Creating directory `%s' for zone files failed!\n"), zonefile_directory);
1765       GNUNET_SCHEDULER_add_now (&cleanup_task, NULL);
1766       return;
1767     }
1768     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Created directory `%s' for zone files\n", zonefile_directory);
1769   }
1770
1771   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Scanning directory `%s' for zone files\n", zonefile_directory);
1772   zonekeys = GNUNET_CONTAINER_multihashmap_create (10);
1773   GNUNET_DISK_directory_scan (zonefile_directory, zonekey_file_it, &counter);
1774   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found %u zone files\n", counter);
1775
1776   /* Loading database plugin */
1777   if (GNUNET_OK !=
1778       GNUNET_CONFIGURATION_get_value_string (cfg, "namestore", "database",
1779                                              &database))
1780     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No database backend configured\n");
1781
1782   GNUNET_asprintf (&db_lib_name, "libgnunet_plugin_namestore_%s", database);
1783   GSN_database = GNUNET_PLUGIN_load (db_lib_name, (void *) GSN_cfg);
1784   GNUNET_free (database);
1785   if (GSN_database == NULL)
1786   {
1787     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not load database backend `%s'\n",
1788         db_lib_name);
1789     GNUNET_SCHEDULER_add_now (&cleanup_task, NULL);
1790     return;
1791   }
1792
1793   /* Configuring server handles */
1794   GNUNET_SERVER_add_handlers (server, handlers);
1795   snc = GNUNET_SERVER_notification_context_create (server, 16);
1796   GNUNET_SERVER_disconnect_notify (server,
1797                                    &client_disconnect_notification,
1798                                    NULL);
1799
1800   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleanup_task,
1801                                 NULL);
1802
1803 }
1804
1805
1806 /**
1807  * The main function for the template service.
1808  *
1809  * @param argc number of arguments from the command line
1810  * @param argv command line arguments
1811  * @return 0 ok, 1 on error
1812  */
1813 int
1814 main (int argc, char *const *argv)
1815 {
1816   return (GNUNET_OK ==
1817           GNUNET_SERVICE_run (argc, argv, "namestore",
1818                               GNUNET_SERVICE_OPTION_NONE, &run, NULL)) ? 0 : 1;
1819 }
1820
1821 /* end of gnunet-service-namestore.c */
1822