fix memory leak and unnecessary allocations
[oweals/gnunet.git] / src / namestore / gnunet-service-namestore.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2012, 2013, 2014 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file namestore/gnunet-service-namestore.c
23  * @brief namestore for the GNUnet naming system
24  * @author Matthias Wachs
25  * @author Christian Grothoff
26  */
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet_dnsparser_lib.h"
30 #include "gnunet_gns_service.h"
31 #include "gnunet_namecache_service.h"
32 #include "gnunet_namestore_service.h"
33 #include "gnunet_namestore_plugin.h"
34 #include "gnunet_signatures.h"
35 #include "namestore.h"
36
37 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
38
39
40 /**
41  * A namestore client
42  */
43 struct NamestoreClient;
44
45
46 /**
47  * A namestore iteration operation.
48  */
49 struct ZoneIteration
50 {
51   /**
52    * Next element in the DLL
53    */
54   struct ZoneIteration *next;
55
56   /**
57    * Previous element in the DLL
58    */
59   struct ZoneIteration *prev;
60
61   /**
62    * Namestore client which intiated this zone iteration
63    */
64   struct NamestoreClient *client;
65
66   /**
67    * The nick to add to the records
68    */
69   struct GNUNET_GNSRECORD_Data *nick;
70
71   /**
72    * Key of the zone we are iterating over.
73    */
74   struct GNUNET_CRYPTO_EcdsaPrivateKey zone;
75
76   /**
77    * The operation id fot the zone iteration in the response for the client
78    */
79   uint32_t request_id;
80
81   /**
82    * Offset of the zone iteration used to address next result of the zone
83    * iteration in the store
84    *
85    * Initialy set to 0 in handle_iteration_start
86    * Incremented with by every call to handle_iteration_next
87    */
88   uint32_t offset;
89
90 };
91
92
93 /**
94  * A namestore client
95  */
96 struct NamestoreClient
97 {
98   /**
99    * Next element in the DLL
100    */
101   struct NamestoreClient *next;
102
103   /**
104    * Previous element in the DLL
105    */
106   struct NamestoreClient *prev;
107
108   /**
109    * The client
110    */
111   struct GNUNET_SERVER_Client *client;
112
113   /**
114    * Head of the DLL of
115    * Zone iteration operations in progress initiated by this client
116    */
117   struct ZoneIteration *op_head;
118
119   /**
120    * Tail of the DLL of
121    * Zone iteration operations in progress initiated by this client
122    */
123   struct ZoneIteration *op_tail;
124 };
125
126
127 /**
128  * A namestore monitor.
129  */
130 struct ZoneMonitor
131 {
132   /**
133    * Next element in the DLL
134    */
135   struct ZoneMonitor *next;
136
137   /**
138    * Previous element in the DLL
139    */
140   struct ZoneMonitor *prev;
141
142   /**
143    * Namestore client which intiated this zone monitor
144    */
145   struct NamestoreClient *nc;
146
147   /**
148    * Private key of the zone.
149    */
150   struct GNUNET_CRYPTO_EcdsaPrivateKey zone;
151
152   /**
153    * Task active during initial iteration.
154    */
155   struct GNUNET_SCHEDULER_Task * task;
156
157   /**
158    * Offset of the zone iteration used to address next result of the zone
159    * iteration in the store
160    *
161    * Initialy set to 0.
162    * Incremented with by every call to #handle_iteration_next
163    */
164   uint32_t offset;
165
166 };
167
168
169 /**
170  * Pending operation on the namecache.
171  */
172 struct CacheOperation
173 {
174
175   /**
176    * Kept in a DLL.
177    */
178   struct CacheOperation *prev;
179
180   /**
181    * Kept in a DLL.
182    */
183   struct CacheOperation *next;
184
185   /**
186    * Handle to namecache queue.
187    */
188   struct GNUNET_NAMECACHE_QueueEntry *qe;
189
190   /**
191    * Client to notify about the result.
192    */
193   struct GNUNET_SERVER_Client *client;
194
195   /**
196    * Client's request ID.
197    */
198   uint32_t rid;
199 };
200
201
202 /**
203  * Public key of all zeros.
204  */
205 static const struct GNUNET_CRYPTO_EcdsaPrivateKey zero;
206
207 /**
208  * Configuration handle.
209  */
210 static const struct GNUNET_CONFIGURATION_Handle *GSN_cfg;
211
212 /**
213  * Namecache handle.
214  */
215 static struct GNUNET_NAMECACHE_Handle *namecache;
216
217 /**
218  * Database handle
219  */
220 static struct GNUNET_NAMESTORE_PluginFunctions *GSN_database;
221
222 /**
223  * Name of the database plugin
224  */
225 static char *db_lib_name;
226
227 /**
228  * Our notification context.
229  */
230 static struct GNUNET_SERVER_NotificationContext *snc;
231
232 /**
233  * Head of the Client DLL
234  */
235 static struct NamestoreClient *client_head;
236
237 /**
238  * Tail of the Client DLL
239  */
240 static struct NamestoreClient *client_tail;
241
242 /**
243  * Head of cop DLL.
244  */
245 static struct CacheOperation *cop_head;
246
247 /**
248  * Tail of cop DLL.
249  */
250 static struct CacheOperation *cop_tail;
251
252 /**
253  * First active zone monitor.
254  */
255 static struct ZoneMonitor *monitor_head;
256
257 /**
258  * Last active zone monitor.
259  */
260 static struct ZoneMonitor *monitor_tail;
261
262 /**
263  * Notification context shared by all monitors.
264  */
265 static struct GNUNET_SERVER_NotificationContext *monitor_nc;
266
267
268
269 /**
270  * Task run during shutdown.
271  *
272  * @param cls unused
273  */
274 static void
275 cleanup_task (void *cls)
276 {
277   struct ZoneIteration *no;
278   struct NamestoreClient *nc;
279   struct CacheOperation *cop;
280
281   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
282               "Stopping namestore service\n");
283   if (NULL != snc)
284   {
285     GNUNET_SERVER_notification_context_destroy (snc);
286     snc = NULL;
287   }
288   while (NULL != (cop = cop_head))
289   {
290     GNUNET_NAMECACHE_cancel (cop->qe);
291     GNUNET_CONTAINER_DLL_remove (cop_head,
292                                  cop_tail,
293                                  cop);
294     GNUNET_free (cop);
295   }
296   GNUNET_NAMECACHE_disconnect (namecache);
297   namecache = NULL;
298   while (NULL != (nc = client_head))
299   {
300     while (NULL != (no = nc->op_head))
301     {
302       GNUNET_CONTAINER_DLL_remove (nc->op_head, nc->op_tail, no);
303       GNUNET_free (no);
304     }
305     GNUNET_CONTAINER_DLL_remove (client_head, client_tail, nc);
306     GNUNET_SERVER_client_set_user_context (nc->client, NULL);
307     GNUNET_free (nc);
308   }
309   GNUNET_break (NULL == GNUNET_PLUGIN_unload (db_lib_name, GSN_database));
310   GNUNET_free (db_lib_name);
311   db_lib_name = NULL;
312   if (NULL != monitor_nc)
313   {
314     GNUNET_SERVER_notification_context_destroy (monitor_nc);
315     monitor_nc = NULL;
316   }
317 }
318
319
320 /**
321  * Called whenever a client is disconnected.
322  * Frees our resources associated with that client.
323  *
324  * @param cls closure
325  * @param client identification of the client
326  */
327 static void
328 client_disconnect_notification (void *cls,
329                                 struct GNUNET_SERVER_Client *client)
330 {
331   struct ZoneIteration *no;
332   struct NamestoreClient *nc;
333   struct ZoneMonitor *zm;
334   struct CacheOperation *cop;
335
336   if (NULL == client)
337     return;
338   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
339               "Client %p disconnected\n",
340               client);
341   if (NULL == (nc = GNUNET_SERVER_client_get_user_context (client, struct NamestoreClient)))
342     return;
343   while (NULL != (no = nc->op_head))
344   {
345     GNUNET_CONTAINER_DLL_remove (nc->op_head, nc->op_tail, no);
346     GNUNET_free (no);
347   }
348   GNUNET_CONTAINER_DLL_remove (client_head, client_tail, nc);
349   GNUNET_free (nc);
350   for (zm = monitor_head; NULL != zm; zm = zm->next)
351   {
352     if (client == zm->nc->client)
353     {
354       GNUNET_CONTAINER_DLL_remove (monitor_head,
355                                    monitor_tail,
356                                    zm);
357       if (NULL != zm->task)
358       {
359         GNUNET_SCHEDULER_cancel (zm->task);
360         zm->task = NULL;
361       }
362       GNUNET_free (zm);
363       break;
364     }
365   }
366   for (cop = cop_head; NULL != cop; cop = cop->next)
367     if (client == cop->client)
368       cop->client = NULL;
369 }
370
371
372 /**
373  * Add a client to our list of active clients, if it is not yet
374  * in there.
375  *
376  * @param client client to add
377  * @return internal namestore client structure for this client
378  */
379 static struct NamestoreClient *
380 client_lookup (struct GNUNET_SERVER_Client *client)
381 {
382   struct NamestoreClient *nc;
383
384   nc = GNUNET_SERVER_client_get_user_context (client, struct NamestoreClient);
385   if (NULL != nc)
386     return nc;
387   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
388               "Client %p connected\n",
389               client);
390   nc = GNUNET_new (struct NamestoreClient);
391   nc->client = client;
392   GNUNET_SERVER_notification_context_add (snc, client);
393   GNUNET_CONTAINER_DLL_insert (client_head, client_tail, nc);
394   GNUNET_SERVER_client_set_user_context (client, nc);
395   return nc;
396 }
397
398
399 /**
400  * Function called with the records for the #GNUNET_GNS_MASTERZONE_STR
401  * label in the zone.  Used to locate the #GNUNET_GNSRECORD_TYPE_NICK
402  * record, which (if found) is then copied to @a cls for future use.
403  *
404  * @param cls a `struct GNUNET_GNSRECORD_Data **` for storing the nick (if found)
405  * @param private_key the private key of the zone (unused)
406  * @param label should be #GNUNET_GNS_MASTERZONE_STR
407  * @param rd_count number of records in @a rd
408  * @param rd records stored under @a label in the zone
409  */
410 static void
411 lookup_nick_it (void *cls,
412                 const struct GNUNET_CRYPTO_EcdsaPrivateKey *private_key,
413                 const char *label,
414                 unsigned int rd_count,
415                 const struct GNUNET_GNSRECORD_Data *rd)
416 {
417   struct GNUNET_GNSRECORD_Data **res = cls;
418   int c;
419
420   if (0 != strcmp (label, GNUNET_GNS_MASTERZONE_STR))
421   {
422     GNUNET_break (0);
423     return;
424   }
425   for (c = 0; c < rd_count; c++)
426   {
427     if (GNUNET_GNSRECORD_TYPE_NICK == rd[c].record_type)
428     {
429       (*res) = GNUNET_malloc (rd[c].data_size + sizeof (struct GNUNET_GNSRECORD_Data));
430       (*res)->data = &(*res)[1];
431       GNUNET_memcpy ((void *) (*res)->data,
432                      rd[c].data,
433                      rd[c].data_size);
434       (*res)->data_size = rd[c].data_size;
435       (*res)->expiration_time = rd[c].expiration_time;
436       (*res)->flags = rd[c].flags;
437       (*res)->record_type = GNUNET_GNSRECORD_TYPE_NICK;
438       return;
439     }
440   }
441   (*res) = NULL;
442 }
443
444
445 /**
446  * Return the NICK record for the zone (if it exists).
447  *
448  * @param zone private key for the zone to look for nick
449  * @return NULL if no NICK record was found
450  */
451 static struct GNUNET_GNSRECORD_Data *
452 get_nick_record (const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone)
453 {
454   struct GNUNET_CRYPTO_EcdsaPublicKey pub;
455   struct GNUNET_GNSRECORD_Data *nick;
456   int res;
457
458   res = GSN_database->lookup_records (GSN_database->cls, zone,
459                                       GNUNET_GNS_MASTERZONE_STR,
460                                       &lookup_nick_it, &nick);
461   if ( (GNUNET_OK != res) ||
462        (NULL == nick) )
463   {
464     GNUNET_CRYPTO_ecdsa_key_get_public (zone, &pub);
465     GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
466                 "No nick name set for zone `%s'\n",
467                 GNUNET_GNSRECORD_z2s (&pub));
468     return NULL;
469   }
470   return nick;
471 }
472
473
474 static void
475 merge_with_nick_records (const struct GNUNET_GNSRECORD_Data *nick_rd,
476                          unsigned int rdc2,
477                          const struct GNUNET_GNSRECORD_Data *rd2,
478                          unsigned int *rdc_res,
479                          struct GNUNET_GNSRECORD_Data **rd_res)
480 {
481   uint64_t latest_expiration;
482   size_t req;
483   char *data;
484   int record_offset;
485   size_t data_offset;
486
487   (*rdc_res) = 1 + rdc2;
488   if (0 == 1 + rdc2)
489   {
490     (*rd_res) = NULL;
491     return;
492   }
493
494   req = 0;
495   for (unsigned int c=0; c< 1; c++)
496     req += sizeof (struct GNUNET_GNSRECORD_Data) + nick_rd[c].data_size;
497   for (unsigned int c=0; c< rdc2; c++)
498     req += sizeof (struct GNUNET_GNSRECORD_Data) + rd2[c].data_size;
499   (*rd_res) = GNUNET_malloc (req);
500   data = (char *) &(*rd_res)[1 + rdc2];
501   data_offset = 0;
502   latest_expiration = 0;
503
504   for (unsigned int c=0; c< rdc2; c++)
505   {
506     if (0 != (rd2[c].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION))
507     {
508       if ((GNUNET_TIME_absolute_get().abs_value_us + rd2[c].expiration_time) >
509         latest_expiration)
510           latest_expiration = rd2[c].expiration_time;
511     }
512     else if (rd2[c].expiration_time > latest_expiration)
513       latest_expiration = rd2[c].expiration_time;
514     (*rd_res)[c] = rd2[c];
515     (*rd_res)[c].data = (void *) &data[data_offset];
516     GNUNET_memcpy ((void *) (*rd_res)[c].data,
517                    rd2[c].data,
518                    rd2[c].data_size);
519     data_offset += (*rd_res)[c].data_size;
520   }
521   record_offset = rdc2;
522   for (unsigned int c=0; c< 1; c++)
523   {
524     (*rd_res)[c+record_offset] = nick_rd[c];
525     (*rd_res)[c+record_offset].expiration_time = latest_expiration;
526     (*rd_res)[c+record_offset].data = (void *) &data[data_offset];
527     GNUNET_memcpy ((void *) (*rd_res)[c+record_offset].data,
528                    nick_rd[c].data,
529                    nick_rd[c].data_size);
530     data_offset += (*rd_res)[c+record_offset].data_size;
531   }
532   GNUNET_assert (req == (sizeof (struct GNUNET_GNSRECORD_Data)) * (*rdc_res) + data_offset);
533 }
534
535
536 /**
537  * Generate a `struct LookupNameResponseMessage` and send it to the
538  * given client using the given notification context.
539  *
540  * @param nc notification context to use
541  * @param client client to unicast to
542  * @param request_id request ID to use
543  * @param zone_key zone key of the zone
544  * @param name name
545  * @param rd_count number of records in @a rd
546  * @param rd array of records
547  */
548 static void
549 send_lookup_response (struct GNUNET_SERVER_NotificationContext *nc,
550                       struct GNUNET_SERVER_Client *client,
551                       uint32_t request_id,
552                       const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
553                       const char *name,
554                       unsigned int rd_count,
555                       const struct GNUNET_GNSRECORD_Data *rd)
556 {
557   struct RecordResultMessage *zir_msg;
558   struct GNUNET_GNSRECORD_Data *nick;
559   struct GNUNET_GNSRECORD_Data *res;
560   unsigned int res_count;
561   size_t name_len;
562   size_t rd_ser_len;
563   size_t msg_size;
564   char *name_tmp;
565   char *rd_ser;
566
567   nick = get_nick_record (zone_key);
568   if ((NULL != nick) && (0 != strcmp(name, GNUNET_GNS_MASTERZONE_STR)))
569   {
570     nick->flags = (nick->flags | GNUNET_GNSRECORD_RF_PRIVATE) ^ GNUNET_GNSRECORD_RF_PRIVATE;
571     merge_with_nick_records (nick,
572                              rd_count,
573                              rd,
574                              &res_count,
575                              &res);
576     GNUNET_free (nick);
577   }
578   else
579   {
580     res_count = rd_count;
581     res = (struct GNUNET_GNSRECORD_Data *) rd;
582   }
583
584   name_len = strlen (name) + 1;
585   rd_ser_len = GNUNET_GNSRECORD_records_get_size (res_count, res);
586   msg_size = sizeof (struct RecordResultMessage) + name_len + rd_ser_len;
587   (void) client_lookup (client);
588   zir_msg = GNUNET_malloc (msg_size);
589   zir_msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT);
590   zir_msg->gns_header.header.size = htons (msg_size);
591   zir_msg->gns_header.r_id = htonl (request_id);
592   zir_msg->name_len = htons (name_len);
593   zir_msg->rd_count = htons (res_count);
594   zir_msg->rd_len = htons (rd_ser_len);
595   zir_msg->private_key = *zone_key;
596   name_tmp = (char *) &zir_msg[1];
597   GNUNET_memcpy (name_tmp, name, name_len);
598   rd_ser = &name_tmp[name_len];
599   GNUNET_GNSRECORD_records_serialize (res_count, res, rd_ser_len, rd_ser);
600   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
601               "Sending RECORD_RESULT message with %u records and size %zu\n",
602               res_count,
603               msg_size);
604   GNUNET_SERVER_notification_context_unicast (nc,
605                                               client,
606                                               &zir_msg->gns_header.header,
607                                               GNUNET_NO);
608   if (rd != res)
609     GNUNET_free (res);
610   GNUNET_free (zir_msg);
611 }
612
613
614 /**
615  * Send response to the store request to the client.
616  *
617  * @param client client to talk to
618  * @param res status of the operation
619  * @param rid client's request ID
620  */
621 static void
622 send_store_response (struct GNUNET_SERVER_Client *client,
623                      int res,
624                      uint32_t rid)
625 {
626   struct RecordStoreResponseMessage rcr_msg;
627
628   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
629               "Sending `%s' message\n",
630               "RECORD_STORE_RESPONSE");
631   rcr_msg.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE_RESPONSE);
632   rcr_msg.gns_header.header.size = htons (sizeof (struct RecordStoreResponseMessage));
633   rcr_msg.gns_header.r_id = htonl (rid);
634   rcr_msg.op_result = htonl (res);
635   GNUNET_SERVER_notification_context_unicast (snc, client,
636                                               &rcr_msg.gns_header.header,
637                                               GNUNET_NO);
638 }
639
640
641 /**
642  * Cache operation complete, clean up.
643  *
644  * @param cls the `struct CacheOperation`
645  * @param success success
646  * @param emsg error messages
647  */
648 static void
649 finish_cache_operation (void *cls,
650                         int32_t success,
651                         const char *emsg)
652 {
653   struct CacheOperation *cop = cls;
654
655   if (NULL != emsg)
656     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
657                 _("Failed to replicate block in namecache: %s\n"),
658                 emsg);
659   else
660     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
661                 "CACHE operation completed\n");
662   GNUNET_CONTAINER_DLL_remove (cop_head,
663                                cop_tail,
664                                cop);
665   if (NULL != cop->client)
666     send_store_response (cop->client,
667                          success,
668                          cop->rid);
669   GNUNET_free (cop);
670 }
671
672
673 /**
674  * We just touched the plaintext information about a name in our zone;
675  * refresh the corresponding (encrypted) block in the namecache.
676  *
677  * @param client client responsible for the request
678  * @param rid request ID of the client
679  * @param zone_key private key of the zone
680  * @param name label for the records
681  * @param rd_count number of records
682  * @param rd records stored under the given @a name
683  */
684 static void
685 refresh_block (struct GNUNET_SERVER_Client *client,
686                uint32_t rid,
687                const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
688                const char *name,
689                unsigned int rd_count,
690                const struct GNUNET_GNSRECORD_Data *rd)
691 {
692   struct GNUNET_GNSRECORD_Block *block;
693   struct CacheOperation *cop;
694   struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
695   struct GNUNET_GNSRECORD_Data *nick;
696   struct GNUNET_GNSRECORD_Data *res;
697   unsigned int res_count;
698
699   nick = get_nick_record (zone_key);
700   res_count = rd_count;
701   res = (struct GNUNET_GNSRECORD_Data *) rd; /* fixme: a bit unclean... */
702   if (NULL != nick)
703   {
704     nick->flags = (nick->flags | GNUNET_GNSRECORD_RF_PRIVATE) ^ GNUNET_GNSRECORD_RF_PRIVATE;
705     merge_with_nick_records (nick, rd_count,rd, &res_count, &res);
706     GNUNET_free (nick);
707   }
708
709   if (0 == res_count)
710     block = GNUNET_GNSRECORD_block_create (zone_key,
711                                            GNUNET_TIME_UNIT_ZERO_ABS,
712                                            name,
713                                            res, rd_count);
714   else
715     block = GNUNET_GNSRECORD_block_create (zone_key,
716                                            GNUNET_GNSRECORD_record_get_expiration_time (res_count,
717                                                res),
718                                            name,
719                                            res, res_count);
720   GNUNET_assert (NULL != block);
721   GNUNET_CRYPTO_ecdsa_key_get_public (zone_key,
722                                       &pkey);
723   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
724               "Caching block for label `%s' with %u records in zone `%s' in namecache\n",
725               name,
726               res_count,
727               GNUNET_GNSRECORD_z2s (&pkey));
728   cop = GNUNET_new (struct CacheOperation);
729   cop->client = client;
730   cop->rid = rid;
731   GNUNET_CONTAINER_DLL_insert (cop_head,
732                                cop_tail,
733                                cop);
734   cop->qe = GNUNET_NAMECACHE_block_cache (namecache,
735                                           block,
736                                           &finish_cache_operation,
737                                           cop);
738   GNUNET_free (block);
739 }
740
741
742 /**
743  * Closure for #lookup_it().
744  */
745 struct RecordLookupContext
746 {
747   const char *label;
748
749   int found;
750
751   unsigned int res_rd_count;
752
753   size_t rd_ser_len;
754
755   char *res_rd;
756
757   struct GNUNET_GNSRECORD_Data *nick;
758 };
759
760
761 static void
762 lookup_it (void *cls,
763            const struct GNUNET_CRYPTO_EcdsaPrivateKey *private_key,
764            const char *label,
765            unsigned int rd_count,
766            const struct GNUNET_GNSRECORD_Data *rd)
767 {
768   struct RecordLookupContext *rlc = cls;
769   struct GNUNET_GNSRECORD_Data *rd_res;
770   unsigned int rdc_res;
771
772   if (0 == strcmp (label, rlc->label))
773   {
774     rlc->found = GNUNET_YES;
775     if (0 != rd_count)
776     {
777       if ( (NULL != rlc->nick) &&
778            (0 != strcmp (label,
779                          GNUNET_GNS_MASTERZONE_STR)) )
780       {
781         /* Merge */
782         rd_res = NULL;
783         rdc_res = 0;
784         rlc->nick->flags = (rlc->nick->flags | GNUNET_GNSRECORD_RF_PRIVATE) ^ GNUNET_GNSRECORD_RF_PRIVATE;
785         merge_with_nick_records (rlc->nick,
786                                  rd_count, rd,
787                                  &rdc_res, &rd_res);
788
789         rlc->rd_ser_len = GNUNET_GNSRECORD_records_get_size (rdc_res,
790                                                              rd_res);
791         rlc->res_rd_count = rdc_res;
792         rlc->res_rd = GNUNET_malloc (rlc->rd_ser_len);
793         GNUNET_GNSRECORD_records_serialize (rdc_res,
794                                             rd_res,
795                                             rlc->rd_ser_len,
796                                             rlc->res_rd);
797
798         GNUNET_free  (rd_res);
799         GNUNET_free  (rlc->nick);
800         rlc->nick = NULL;
801       }
802       else
803       {
804         rlc->rd_ser_len = GNUNET_GNSRECORD_records_get_size (rd_count,
805                                                              rd);
806         rlc->res_rd_count = rd_count;
807         rlc->res_rd = GNUNET_malloc (rlc->rd_ser_len);
808         GNUNET_GNSRECORD_records_serialize (rd_count,
809                                             rd,
810                                             rlc->rd_ser_len,
811                                             rlc->res_rd);
812       }
813     }
814     else
815     {
816       rlc->rd_ser_len = 0;
817       rlc->res_rd_count = 0;
818       rlc->res_rd = NULL;
819     }
820   }
821 }
822
823
824 /**
825  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_LOOKUP message
826  *
827  * @param cls unused
828  * @param client client sending the message
829  * @param message message of type 'struct RecordCreateMessage'
830  */
831 static void
832 handle_record_lookup (void *cls,
833                      struct GNUNET_SERVER_Client *client,
834                      const struct GNUNET_MessageHeader *message)
835 {
836   const struct LabelLookupMessage *ll_msg;
837   struct LabelLookupResponseMessage *llr_msg;
838   struct RecordLookupContext rlc;
839   const char *name_tmp;
840   char *res_name;
841   char *conv_name;
842   uint32_t name_len;
843   size_t src_size;
844   size_t res_size;
845   int res;
846
847   if (ntohs (message->size) < sizeof (struct LabelLookupMessage))
848   {
849     GNUNET_break (0);
850     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
851     return;
852   }
853
854   ll_msg = (const struct LabelLookupMessage *) message;
855   name_len = ntohl (ll_msg->label_len);
856   src_size = ntohs (message->size);
857
858   if (name_len !=  src_size - sizeof (struct LabelLookupMessage))
859   {
860     GNUNET_break (0);
861     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
862     return;
863   }
864
865   name_tmp = (const char *) &ll_msg[1];
866   if ('\0' != name_tmp[name_len -1])
867   {
868     GNUNET_break (0);
869     GNUNET_SERVER_receive_done (client,
870                                 GNUNET_SYSERR);
871     return;
872   }
873
874   GNUNET_SERVER_receive_done (client,
875                               GNUNET_OK);
876   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
877               "Received NAMESTORE_RECORD_LOOKUP message for name `%s'\n",
878               name_tmp);
879
880   if (NULL == (client_lookup (client)))
881   {
882     GNUNET_break (0);
883     GNUNET_SERVER_receive_done (client,
884                                 GNUNET_SYSERR);
885     return;
886   }
887
888   conv_name = GNUNET_GNSRECORD_string_to_lowercase (name_tmp);
889   if (NULL == conv_name)
890   {
891     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
892                 "Error converting name `%s'\n",
893                 name_tmp);
894     GNUNET_SERVER_receive_done (client,
895                                 GNUNET_SYSERR);
896     return;
897   }
898   rlc.label = conv_name;
899   rlc.found = GNUNET_NO;
900   rlc.res_rd_count = 0;
901   rlc.res_rd = NULL;
902   rlc.rd_ser_len = 0;
903   rlc.nick = get_nick_record (&ll_msg->zone);
904   res = GSN_database->lookup_records (GSN_database->cls,
905                                       &ll_msg->zone,
906                                       conv_name,
907                                       &lookup_it,
908                                       &rlc);
909   GNUNET_free (conv_name);
910   res_size = sizeof (struct LabelLookupResponseMessage) + name_len + rlc.rd_ser_len;
911   llr_msg = GNUNET_malloc (res_size);
912   llr_msg->gns_header.header.size = htons (res_size);
913   llr_msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_LOOKUP_RESPONSE);
914   llr_msg->gns_header.r_id = ll_msg->gns_header.r_id;
915   llr_msg->private_key = ll_msg->zone;
916   llr_msg->name_len = htons (name_len);
917   llr_msg->rd_count = htons (rlc.res_rd_count);
918   llr_msg->rd_len = htons (rlc.rd_ser_len);
919   res_name = (char *) &llr_msg[1];
920   if  ((GNUNET_YES == rlc.found) && (GNUNET_OK == res))
921     llr_msg->found = ntohs (GNUNET_YES);
922   else
923     llr_msg->found = ntohs (GNUNET_NO);
924   GNUNET_memcpy (&llr_msg[1],
925                  name_tmp,
926                  name_len);
927   GNUNET_memcpy (&res_name[name_len],
928                  rlc.res_rd,
929                  rlc.rd_ser_len);
930   GNUNET_SERVER_notification_context_unicast (snc,
931                                               client,
932                                               &llr_msg->gns_header.header,
933                                               GNUNET_NO);
934   GNUNET_free_non_null (rlc.res_rd);
935   GNUNET_free (llr_msg);
936 }
937
938
939 /**
940  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE message
941  *
942  * @param cls unused
943  * @param client client sending the message
944  * @param message message of type 'struct RecordCreateMessage'
945  */
946 static void
947 handle_record_store (void *cls,
948                      struct GNUNET_SERVER_Client *client,
949                      const struct GNUNET_MessageHeader *message)
950 {
951   const struct RecordStoreMessage *rp_msg;
952   size_t name_len;
953   size_t msg_size;
954   size_t msg_size_exp;
955   size_t rd_ser_len;
956   uint32_t rid;
957   const char *name_tmp;
958   char *conv_name;
959   const char *rd_ser;
960   unsigned int rd_count;
961   int res;
962   struct GNUNET_CRYPTO_EcdsaPublicKey pubkey;
963   struct ZoneMonitor *zm;
964
965   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
966               "Received NAMESTORE_RECORD_STORE message\n");
967   if (ntohs (message->size) < sizeof (struct RecordStoreMessage))
968   {
969     GNUNET_break (0);
970     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
971     return;
972   }
973   rp_msg = (const struct RecordStoreMessage *) message;
974   rid = ntohl (rp_msg->gns_header.r_id);
975   name_len = ntohs (rp_msg->name_len);
976   msg_size = ntohs (message->size);
977   rd_count = ntohs (rp_msg->rd_count);
978   rd_ser_len = ntohs (rp_msg->rd_len);
979   GNUNET_break (0 == ntohs (rp_msg->reserved));
980   msg_size_exp = sizeof (struct RecordStoreMessage) + name_len + rd_ser_len;
981   if (msg_size != msg_size_exp)
982   {
983     GNUNET_break (0);
984     GNUNET_SERVER_receive_done (client,
985                                 GNUNET_SYSERR);
986     return;
987   }
988   if ((0 == name_len) || (name_len > MAX_NAME_LEN))
989   {
990     GNUNET_break (0);
991     GNUNET_SERVER_receive_done (client,
992                                 GNUNET_SYSERR);
993     return;
994   }
995   name_tmp = (const char *) &rp_msg[1];
996   rd_ser = &name_tmp[name_len];
997   if ('\0' != name_tmp[name_len -1])
998   {
999     GNUNET_break (0);
1000     GNUNET_SERVER_receive_done (client,
1001                                 GNUNET_SYSERR);
1002     return;
1003   }
1004   (void) client_lookup (client);
1005   {
1006     struct GNUNET_GNSRECORD_Data rd[rd_count];
1007
1008     if (GNUNET_OK !=
1009         GNUNET_GNSRECORD_records_deserialize (rd_ser_len,
1010                                               rd_ser,
1011                                               rd_count,
1012                                               rd))
1013     {
1014       GNUNET_break (0);
1015       GNUNET_SERVER_receive_done (client,
1016                                   GNUNET_SYSERR);
1017       return;
1018     }
1019
1020     /* Extracting and converting private key */
1021     GNUNET_CRYPTO_ecdsa_key_get_public (&rp_msg->private_key,
1022                                         &pubkey);
1023     conv_name = GNUNET_GNSRECORD_string_to_lowercase (name_tmp);
1024     if (NULL == conv_name)
1025     {
1026       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1027                   "Error converting name `%s'\n",
1028                   name_tmp);
1029       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1030       return;
1031     }
1032     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1033                 "Creating %u records for name `%s' in zone `%s'\n",
1034                 (unsigned int) rd_count,
1035                 conv_name,
1036                 GNUNET_GNSRECORD_z2s (&pubkey));
1037
1038     if ( (0 == rd_count) &&
1039          (GNUNET_NO ==
1040           GSN_database->iterate_records (GSN_database->cls,
1041                                          &rp_msg->private_key,
1042                                          0,
1043                                          NULL,
1044                                          0)) )
1045     {
1046       /* This name does not exist, so cannot be removed */
1047       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1048                   "Name `%s' does not exist, no deletion required\n",
1049                   conv_name);
1050       res = GNUNET_NO;
1051     }
1052     else
1053     {
1054       struct GNUNET_GNSRECORD_Data rd_clean[rd_count];
1055       unsigned int i;
1056       unsigned int rd_clean_off;
1057
1058       /* remove "NICK" records, unless this is for the "+" label */
1059       rd_clean_off = 0;
1060       for (i=0;i<rd_count;i++)
1061       {
1062         rd_clean[rd_clean_off] = rd[i];
1063         if ( (0 == strcmp (GNUNET_GNS_MASTERZONE_STR,
1064                            conv_name)) ||
1065              (GNUNET_GNSRECORD_TYPE_NICK != rd[i].record_type) )
1066           rd_clean_off++;
1067       }
1068       res = GSN_database->store_records (GSN_database->cls,
1069                                          &rp_msg->private_key,
1070                                          conv_name,
1071                                          rd_clean_off,
1072                                          rd_clean);
1073       if (GNUNET_OK == res)
1074       {
1075         for (zm = monitor_head; NULL != zm; zm = zm->next)
1076         {
1077           if ( (0 == memcmp (&rp_msg->private_key, &zm->zone,
1078                              sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey))) ||
1079                (0 == memcmp (&zm->zone,
1080                              &zero,
1081                              sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey))) )
1082           {
1083             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1084                         "Notifying monitor about changes under label `%s'\n",
1085                         conv_name);
1086             send_lookup_response (monitor_nc,
1087                                   zm->nc->client,
1088                                   0,
1089                                   &rp_msg->private_key,
1090                                   conv_name,
1091                                   rd_count, rd);
1092           }
1093           else
1094             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1095                         "Monitor is for another zone\n");
1096         }
1097         if (NULL == monitor_head)
1098           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1099                       "No monitors active\n");
1100       }
1101       else
1102       {
1103         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1104                     "Error storing record: %d\n",
1105                     res);
1106       }
1107     }
1108     if (GNUNET_OK == res)
1109     {
1110       refresh_block (client, rid,
1111                      &rp_msg->private_key,
1112                      conv_name,
1113                      rd_count, rd);
1114       GNUNET_SERVER_receive_done (client,
1115                                   GNUNET_OK);
1116       GNUNET_free (conv_name);
1117       return;
1118     }
1119     GNUNET_free (conv_name);
1120   }
1121   send_store_response (client,
1122                        res,
1123                        rid);
1124   GNUNET_SERVER_receive_done (client,
1125                               GNUNET_OK);
1126 }
1127
1128
1129 /**
1130  * Context for record remove operations passed from #handle_zone_to_name to
1131  * #handle_zone_to_name_it as closure
1132  */
1133 struct ZoneToNameCtx
1134 {
1135   /**
1136    * Namestore client
1137    */
1138   struct NamestoreClient *nc;
1139
1140   /**
1141    * Request id (to be used in the response to the client).
1142    */
1143   uint32_t rid;
1144
1145   /**
1146    * Set to #GNUNET_OK on success, #GNUNET_SYSERR on error.  Note that
1147    * not finding a name for the zone still counts as a 'success' here,
1148    * as this field is about the success of executing the IPC protocol.
1149    */
1150   int success;
1151 };
1152
1153
1154 /**
1155  * Zone to name iterator
1156  *
1157  * @param cls struct ZoneToNameCtx *
1158  * @param zone_key the zone key
1159  * @param name name
1160  * @param rd_count number of records in @a rd
1161  * @param rd record data
1162  */
1163 static void
1164 handle_zone_to_name_it (void *cls,
1165                         const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
1166                         const char *name,
1167                         unsigned int rd_count,
1168                         const struct GNUNET_GNSRECORD_Data *rd)
1169 {
1170   struct ZoneToNameCtx *ztn_ctx = cls;
1171   struct ZoneToNameResponseMessage *ztnr_msg;
1172   int16_t res;
1173   size_t name_len;
1174   size_t rd_ser_len;
1175   size_t msg_size;
1176   char *name_tmp;
1177   char *rd_tmp;
1178
1179   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1180               "Found result for zone-to-name lookup: `%s'\n",
1181               name);
1182   res = GNUNET_YES;
1183   name_len = (NULL == name) ? 0 : strlen (name) + 1;
1184   rd_ser_len = GNUNET_GNSRECORD_records_get_size (rd_count, rd);
1185   msg_size = sizeof (struct ZoneToNameResponseMessage) + name_len + rd_ser_len;
1186   if (msg_size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1187   {
1188     GNUNET_break (0);
1189     ztn_ctx->success = GNUNET_SYSERR;
1190     return;
1191   }
1192   ztnr_msg = GNUNET_malloc (msg_size);
1193   ztnr_msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME_RESPONSE);
1194   ztnr_msg->gns_header.header.size = htons (msg_size);
1195   ztnr_msg->gns_header.r_id = htonl (ztn_ctx->rid);
1196   ztnr_msg->res = htons (res);
1197   ztnr_msg->rd_len = htons (rd_ser_len);
1198   ztnr_msg->rd_count = htons (rd_count);
1199   ztnr_msg->name_len = htons (name_len);
1200   ztnr_msg->zone = *zone_key;
1201   name_tmp = (char *) &ztnr_msg[1];
1202   if (NULL != name)
1203     GNUNET_memcpy (name_tmp, name, name_len);
1204   rd_tmp = &name_tmp[name_len];
1205   GNUNET_GNSRECORD_records_serialize (rd_count, rd, rd_ser_len, rd_tmp);
1206   ztn_ctx->success = GNUNET_OK;
1207   GNUNET_SERVER_notification_context_unicast (snc, ztn_ctx->nc->client,
1208                                               &ztnr_msg->gns_header.header,
1209                                               GNUNET_NO);
1210   GNUNET_free (ztnr_msg);
1211 }
1212
1213
1214 /**
1215  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME message
1216  *
1217  * @param cls unused
1218  * @param client client sending the message
1219  * @param message message of type 'struct ZoneToNameMessage'
1220  */
1221 static void
1222 handle_zone_to_name (void *cls,
1223                      struct GNUNET_SERVER_Client *client,
1224                      const struct GNUNET_MessageHeader *message)
1225 {
1226   struct NamestoreClient *nc;
1227   const struct ZoneToNameMessage *ztn_msg;
1228   struct ZoneToNameCtx ztn_ctx;
1229   struct ZoneToNameResponseMessage ztnr_msg;
1230
1231   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1232               "Received `%s' message\n",
1233               "ZONE_TO_NAME");
1234   ztn_msg = (const struct ZoneToNameMessage *) message;
1235   nc = client_lookup (client);
1236   ztn_ctx.rid = ntohl (ztn_msg->gns_header.r_id);
1237   ztn_ctx.nc = nc;
1238   ztn_ctx.success = GNUNET_NO;
1239   if (GNUNET_SYSERR ==
1240       GSN_database->zone_to_name (GSN_database->cls,
1241                                   &ztn_msg->zone,
1242                                   &ztn_msg->value_zone,
1243                                   &handle_zone_to_name_it, &ztn_ctx))
1244   {
1245     /* internal error, hang up instead of signalling something
1246        that might be wrong */
1247     GNUNET_break (0);
1248     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1249     return;
1250   }
1251   if (GNUNET_NO == ztn_ctx.success)
1252   {
1253     /* no result found, send empty response */
1254     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1255                 "Found no result for zone-to-name lookup.\n");
1256     memset (&ztnr_msg, 0, sizeof (ztnr_msg));
1257     ztnr_msg.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME_RESPONSE);
1258     ztnr_msg.gns_header.header.size = htons (sizeof (ztnr_msg));
1259     ztnr_msg.gns_header.r_id = ztn_msg->gns_header.r_id;
1260     ztnr_msg.res = htons (GNUNET_NO);
1261     GNUNET_SERVER_notification_context_unicast (snc,
1262                                                 client,
1263                                                 &ztnr_msg.gns_header.header,
1264                                                 GNUNET_NO);
1265   }
1266   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1267 }
1268
1269
1270 /**
1271  * Zone iteration processor result
1272  */
1273 enum ZoneIterationResult
1274 {
1275   /**
1276    * Iteration start.
1277    */
1278   IT_START = 0,
1279
1280   /**
1281    * Found records,
1282    * Continue to iterate with next iteration_next call
1283    */
1284   IT_SUCCESS_MORE_AVAILABLE = 1,
1285
1286   /**
1287    * Iteration complete
1288    */
1289   IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE = 2
1290 };
1291
1292
1293 /**
1294  * Context for record remove operations passed from
1295  * #run_zone_iteration_round to #zone_iterate_proc as closure
1296  */
1297 struct ZoneIterationProcResult
1298 {
1299   /**
1300    * The zone iteration handle
1301    */
1302   struct ZoneIteration *zi;
1303
1304   /**
1305    * Iteration result: iteration done?
1306    * #IT_SUCCESS_MORE_AVAILABLE:  if there may be more results overall but
1307    * we got one for now and have sent it to the client
1308    * #IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE: if there are no further results,
1309    * #IT_START: if we are still trying to find a result.
1310    */
1311   int res_iteration_finished;
1312
1313 };
1314
1315
1316 /**
1317  * Process results for zone iteration from database
1318  *
1319  * @param cls struct ZoneIterationProcResult *proc
1320  * @param zone_key the zone key
1321  * @param name name
1322  * @param rd_count number of records for this name
1323  * @param rd record data
1324  */
1325 static void
1326 zone_iterate_proc (void *cls,
1327                        const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
1328                        const char *name,
1329                        unsigned int rd_count,
1330                        const struct GNUNET_GNSRECORD_Data *rd)
1331 {
1332   struct ZoneIterationProcResult *proc = cls;
1333   unsigned int i;
1334   int do_refresh_block;
1335
1336   if ((NULL == zone_key) && (NULL == name))
1337   {
1338     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1339                 "Iteration done\n");
1340     proc->res_iteration_finished = IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE;
1341     return;
1342   }
1343   if ((NULL == zone_key) || (NULL == name))
1344   {
1345     /* what is this!? should never happen */
1346     proc->res_iteration_finished = IT_START;
1347     GNUNET_break (0);
1348     return;
1349   }
1350   proc->res_iteration_finished = IT_SUCCESS_MORE_AVAILABLE;
1351   send_lookup_response (snc,
1352                         proc->zi->client->client,
1353                         proc->zi->request_id,
1354                         zone_key,
1355                         name,
1356                         rd_count,
1357                         rd);
1358   do_refresh_block = GNUNET_NO;
1359   for (i=0;i<rd_count;i++)
1360     if (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION))
1361     {
1362       do_refresh_block = GNUNET_YES;
1363       break;
1364     }
1365   if (GNUNET_YES == do_refresh_block)
1366     refresh_block (NULL, 0,
1367                    zone_key,
1368                    name,
1369                    rd_count,
1370                    rd);
1371
1372 }
1373
1374
1375 /**
1376  * Perform the next round of the zone iteration.
1377  *
1378  * @param zi zone iterator to process
1379  */
1380 static void
1381 run_zone_iteration_round (struct ZoneIteration *zi)
1382 {
1383   struct ZoneIterationProcResult proc;
1384   struct RecordResultMessage rrm;
1385   int ret;
1386
1387   memset (&proc, 0, sizeof (proc));
1388   proc.zi = zi;
1389   proc.res_iteration_finished = IT_START;
1390   while (IT_START == proc.res_iteration_finished)
1391   {
1392     if (GNUNET_SYSERR ==
1393         (ret = GSN_database->iterate_records (GSN_database->cls,
1394                                               (0 == memcmp (&zi->zone, &zero, sizeof (zero)))
1395                                               ? NULL
1396                                               : &zi->zone,
1397                                               zi->offset,
1398                                               &zone_iterate_proc, &proc)))
1399     {
1400       GNUNET_break (0);
1401       break;
1402     }
1403     if (GNUNET_NO == ret)
1404       proc.res_iteration_finished = IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE;
1405     zi->offset++;
1406   }
1407   if (IT_SUCCESS_MORE_AVAILABLE == proc.res_iteration_finished)
1408   {
1409     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1410                 "More results available\n");
1411     return; /* more results later */
1412   }
1413   /* send empty response to indicate end of list */
1414   memset (&rrm, 0, sizeof (rrm));
1415   rrm.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT);
1416   rrm.gns_header.header.size = htons (sizeof (rrm));
1417   rrm.gns_header.r_id = htonl (zi->request_id);
1418   GNUNET_SERVER_notification_context_unicast (snc,
1419                                               zi->client->client,
1420                                               &rrm.gns_header.header,
1421                                               GNUNET_NO);
1422   GNUNET_CONTAINER_DLL_remove (zi->client->op_head,
1423                                zi->client->op_tail,
1424                                zi);
1425   GNUNET_free (zi);
1426 }
1427
1428
1429 /**
1430  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_START message
1431  *
1432  * @param cls unused
1433  * @param client the client sending the message
1434  * @param message message of type 'struct ZoneIterationStartMessage'
1435  */
1436 static void
1437 handle_iteration_start (void *cls,
1438                         struct GNUNET_SERVER_Client *client,
1439                         const struct GNUNET_MessageHeader *message)
1440 {
1441   const struct ZoneIterationStartMessage *zis_msg;
1442   struct NamestoreClient *nc;
1443   struct ZoneIteration *zi;
1444
1445   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "ZONE_ITERATION_START");
1446   if (NULL == (nc = client_lookup (client)))
1447   {
1448     GNUNET_break (0);
1449     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1450     return;
1451   }
1452   zis_msg = (const struct ZoneIterationStartMessage *) message;
1453   zi = GNUNET_new (struct ZoneIteration);
1454   zi->request_id = ntohl (zis_msg->gns_header.r_id);
1455   zi->offset = 0;
1456   zi->client = nc;
1457   zi->zone = zis_msg->zone;
1458
1459
1460   GNUNET_CONTAINER_DLL_insert (nc->op_head, nc->op_tail, zi);
1461   run_zone_iteration_round (zi);
1462   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1463 }
1464
1465
1466 /**
1467  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_STOP message
1468  *
1469  * @param cls unused
1470  * @param client GNUNET_SERVER_Client sending the message
1471  * @param message message of type 'struct ZoneIterationStopMessage'
1472  */
1473 static void
1474 handle_iteration_stop (void *cls,
1475                        struct GNUNET_SERVER_Client *client,
1476                        const struct GNUNET_MessageHeader *message)
1477 {
1478   struct NamestoreClient *nc;
1479   struct ZoneIteration *zi;
1480   const struct ZoneIterationStopMessage *zis_msg;
1481   uint32_t rid;
1482
1483   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1484               "Received `%s' message\n",
1485               "ZONE_ITERATION_STOP");
1486   if (NULL == (nc = client_lookup(client)))
1487   {
1488     GNUNET_break (0);
1489     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1490     return;
1491   }
1492   zis_msg = (const struct ZoneIterationStopMessage *) message;
1493   rid = ntohl (zis_msg->gns_header.r_id);
1494   for (zi = nc->op_head; NULL != zi; zi = zi->next)
1495     if (zi->request_id == rid)
1496       break;
1497   if (NULL == zi)
1498   {
1499     GNUNET_break (0);
1500     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1501     return;
1502   }
1503   GNUNET_CONTAINER_DLL_remove (nc->op_head, nc->op_tail, zi);
1504   GNUNET_free (zi);
1505   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1506 }
1507
1508
1509 /**
1510  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_NEXT message
1511  *
1512  * @param cls unused
1513  * @param client GNUNET_SERVER_Client sending the message
1514  * @param message message of type 'struct ZoneIterationNextMessage'
1515  */
1516 static void
1517 handle_iteration_next (void *cls,
1518                        struct GNUNET_SERVER_Client *client,
1519                        const struct GNUNET_MessageHeader *message)
1520 {
1521   struct NamestoreClient *nc;
1522   struct ZoneIteration *zi;
1523   const struct ZoneIterationNextMessage *zis_msg;
1524   uint32_t rid;
1525
1526   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1527               "Received `%s' message\n",
1528               "ZONE_ITERATION_NEXT");
1529   if (NULL == (nc = client_lookup(client)))
1530   {
1531     GNUNET_break (0);
1532     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1533     return;
1534   }
1535   zis_msg = (const struct ZoneIterationNextMessage *) message;
1536   rid = ntohl (zis_msg->gns_header.r_id);
1537   for (zi = nc->op_head; NULL != zi; zi = zi->next)
1538     if (zi->request_id == rid)
1539       break;
1540   if (NULL == zi)
1541   {
1542     GNUNET_break (0);
1543     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1544     return;
1545   }
1546   run_zone_iteration_round (zi);
1547   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1548 }
1549
1550
1551 /**
1552  * Send 'sync' message to zone monitor, we're now in sync.
1553  *
1554  * @param zm monitor that is now in sync
1555  */
1556 static void
1557 monitor_sync (struct ZoneMonitor *zm)
1558 {
1559   struct GNUNET_MessageHeader sync;
1560
1561   sync.size = htons (sizeof (struct GNUNET_MessageHeader));
1562   sync.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_SYNC);
1563   GNUNET_SERVER_notification_context_unicast (monitor_nc,
1564                                               zm->nc->client,
1565                                               &sync,
1566                                               GNUNET_NO);
1567 }
1568
1569
1570 /**
1571  * Obtain the next datum during the zone monitor's zone intiial iteration.
1572  *
1573  * @param cls zone monitor that does its initial iteration
1574  */
1575 static void
1576 monitor_next (void *cls);
1577
1578
1579 /**
1580  * A #GNUNET_NAMESTORE_RecordIterator for monitors.
1581  *
1582  * @param cls a 'struct ZoneMonitor *' with information about the monitor
1583  * @param zone_key zone key of the zone
1584  * @param name name
1585  * @param rd_count number of records in @a rd
1586  * @param rd array of records
1587  */
1588 static void
1589 monitor_iterate_cb (void *cls,
1590                     const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
1591                     const char *name,
1592                     unsigned int rd_count,
1593                     const struct GNUNET_GNSRECORD_Data *rd)
1594 {
1595   struct ZoneMonitor *zm = cls;
1596
1597   if (NULL == name)
1598   {
1599     /* finished with iteration */
1600     monitor_sync (zm);
1601     return;
1602   }
1603   send_lookup_response (monitor_nc,
1604                         zm->nc->client,
1605                         0,
1606                         zone_key,
1607                         name,
1608                         rd_count,
1609                         rd);
1610   zm->task = GNUNET_SCHEDULER_add_now (&monitor_next, zm);
1611 }
1612
1613
1614 /**
1615  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_START message
1616  *
1617  * @param cls unused
1618  * @param client the client sending the message
1619  * @param message message of type 'struct ZoneMonitorStartMessage'
1620  */
1621 static void
1622 handle_monitor_start (void *cls,
1623                       struct GNUNET_SERVER_Client *client,
1624                       const struct GNUNET_MessageHeader *message)
1625 {
1626   const struct ZoneMonitorStartMessage *zis_msg;
1627   struct ZoneMonitor *zm;
1628
1629   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1630               "Received `%s' message\n",
1631               "ZONE_MONITOR_START");
1632   zis_msg = (const struct ZoneMonitorStartMessage *) message;
1633   zm = GNUNET_new (struct ZoneMonitor);
1634   zm->offset = 0;
1635   zm->nc = client_lookup (client);
1636   zm->zone = zis_msg->zone;
1637   GNUNET_CONTAINER_DLL_insert (monitor_head, monitor_tail, zm);
1638   GNUNET_SERVER_client_mark_monitor (client);
1639   GNUNET_SERVER_disable_receive_done_warning (client);
1640   GNUNET_SERVER_notification_context_add (monitor_nc,
1641                                           client);
1642   if (GNUNET_YES == ntohl (zis_msg->iterate_first))
1643     zm->task = GNUNET_SCHEDULER_add_now (&monitor_next, zm);
1644   else
1645     monitor_sync (zm);
1646 }
1647
1648
1649 /**
1650  * Obtain the next datum during the zone monitor's zone intiial iteration.
1651  *
1652  * @param cls zone monitor that does its initial iteration
1653  */
1654 static void
1655 monitor_next (void *cls)
1656 {
1657   struct ZoneMonitor *zm = cls;
1658   int ret;
1659
1660   zm->task = NULL;
1661   ret = GSN_database->iterate_records (GSN_database->cls,
1662                                        (0 == memcmp (&zm->zone, &zero, sizeof (zero)))
1663                                        ? NULL
1664                                        : &zm->zone,
1665                                        zm->offset++,
1666                                        &monitor_iterate_cb, zm);
1667   if (GNUNET_SYSERR == ret)
1668   {
1669     GNUNET_SERVER_client_disconnect (zm->nc->client);
1670     return;
1671   }
1672   if (GNUNET_NO == ret)
1673   {
1674     /* empty zone */
1675     monitor_sync (zm);
1676     return;
1677   }
1678 }
1679
1680
1681 /**
1682  * Process namestore requests.
1683  *
1684  * @param cls closure
1685  * @param server the initialized server
1686  * @param cfg configuration to use
1687  */
1688 static void
1689 run (void *cls, struct GNUNET_SERVER_Handle *server,
1690      const struct GNUNET_CONFIGURATION_Handle *cfg)
1691 {
1692   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1693     {&handle_record_store, NULL,
1694      GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE, 0},
1695     {&handle_record_lookup, NULL,
1696      GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_LOOKUP, 0},
1697     {&handle_zone_to_name, NULL,
1698      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME, sizeof (struct ZoneToNameMessage) },
1699     {&handle_iteration_start, NULL,
1700      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_START, sizeof (struct ZoneIterationStartMessage) },
1701     {&handle_iteration_next, NULL,
1702      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_NEXT, sizeof (struct ZoneIterationNextMessage) },
1703     {&handle_iteration_stop, NULL,
1704      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_STOP, sizeof (struct ZoneIterationStopMessage) },
1705     {&handle_monitor_start, NULL,
1706      GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_START, sizeof (struct ZoneMonitorStartMessage) },
1707     {NULL, NULL, 0, 0}
1708   };
1709   char *database;
1710
1711   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting namestore service\n");
1712   GSN_cfg = cfg;
1713   monitor_nc = GNUNET_SERVER_notification_context_create (server, 1);
1714   namecache = GNUNET_NAMECACHE_connect (cfg);
1715   /* Loading database plugin */
1716   if (GNUNET_OK !=
1717       GNUNET_CONFIGURATION_get_value_string (cfg,
1718                                              "namestore",
1719                                              "database",
1720                                              &database))
1721     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1722                 "No database backend configured\n");
1723
1724   GNUNET_asprintf (&db_lib_name,
1725                    "libgnunet_plugin_namestore_%s",
1726                    database);
1727   GSN_database = GNUNET_PLUGIN_load (db_lib_name,
1728                                      (void *) GSN_cfg);
1729   GNUNET_free (database);
1730   if (NULL == GSN_database)
1731   {
1732     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1733                 "Could not load database backend `%s'\n",
1734                 db_lib_name);
1735     GNUNET_SCHEDULER_add_now (&cleanup_task, NULL);
1736     return;
1737   }
1738
1739   /* Configuring server handles */
1740   GNUNET_SERVER_add_handlers (server, handlers);
1741   snc = GNUNET_SERVER_notification_context_create (server, 16);
1742   GNUNET_SERVER_disconnect_notify (server,
1743                                    &client_disconnect_notification,
1744                                    NULL);
1745   GNUNET_SCHEDULER_add_shutdown (&cleanup_task,
1746                                  NULL);
1747 }
1748
1749
1750 /**
1751  * The main function for the template service.
1752  *
1753  * @param argc number of arguments from the command line
1754  * @param argv command line arguments
1755  * @return 0 ok, 1 on error
1756  */
1757 int
1758 main (int argc, char *const *argv)
1759 {
1760   return (GNUNET_OK ==
1761           GNUNET_SERVICE_run (argc, argv, "namestore",
1762                               GNUNET_SERVICE_OPTION_NONE, &run, NULL)) ? 0 : 1;
1763 }
1764
1765 /* end of gnunet-service-namestore.c */