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