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