- Tests did not clean up: TEST_HOME with namestore db was not removed after test
[oweals/gnunet.git] / src / namestore / gnunet-service-namestore.c
1 /*
2      This file is part of GNUnet.
3      (C) 2012, 2013 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  * @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   GNUNET_SCHEDULER_TaskIdentifier 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  * @param tc unused
274  */
275 static void
276 cleanup_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
277 {
278   struct ZoneIteration *no;
279   struct NamestoreClient *nc;
280   struct CacheOperation *cop;
281
282   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
283               "Stopping namestore service\n");
284   if (NULL != snc)
285   {
286     GNUNET_SERVER_notification_context_destroy (snc);
287     snc = NULL;
288   }
289   while (NULL != (cop = cop_head))
290   {
291     GNUNET_NAMECACHE_cancel (cop->qe);
292     GNUNET_CONTAINER_DLL_remove (cop_head,
293                                  cop_tail,
294                                  cop);
295     GNUNET_free (cop);
296   }
297   GNUNET_NAMECACHE_disconnect (namecache);
298   namecache = NULL;
299   while (NULL != (nc = client_head))
300   {
301     while (NULL != (no = nc->op_head))
302     {
303       GNUNET_CONTAINER_DLL_remove (nc->op_head, nc->op_tail, no);
304       GNUNET_free (no);
305     }
306     GNUNET_CONTAINER_DLL_remove (client_head, client_tail, nc);
307     GNUNET_SERVER_client_set_user_context (nc->client, (void *)NULL);
308     GNUNET_free (nc);
309   }
310   GNUNET_break (NULL == GNUNET_PLUGIN_unload (db_lib_name, GSN_database));
311   GNUNET_free (db_lib_name);
312   db_lib_name = NULL;
313   if (NULL != monitor_nc)
314   {
315     GNUNET_SERVER_notification_context_destroy (monitor_nc);
316     monitor_nc = NULL;
317   }
318 }
319
320
321 /**
322  * Called whenever a client is disconnected.
323  * Frees our resources associated with that client.
324  *
325  * @param cls closure
326  * @param client identification of the client
327  */
328 static void
329 client_disconnect_notification (void *cls,
330                                 struct GNUNET_SERVER_Client *client)
331 {
332   struct ZoneIteration *no;
333   struct NamestoreClient *nc;
334   struct ZoneMonitor *zm;
335   struct CacheOperation *cop;
336
337   if (NULL == client)
338     return;
339   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
340               "Client %p disconnected\n",
341               client);
342   if (NULL == (nc = GNUNET_SERVER_client_get_user_context (client, struct NamestoreClient)))
343     return;
344   while (NULL != (no = nc->op_head))
345   {
346     GNUNET_CONTAINER_DLL_remove (nc->op_head, nc->op_tail, no);
347     GNUNET_free (no);
348   }
349   GNUNET_CONTAINER_DLL_remove (client_head, client_tail, nc);
350   GNUNET_free (nc);
351   for (zm = monitor_head; NULL != zm; zm = zm->next)
352   {
353     if (client == zm->nc->client)
354     {
355       GNUNET_CONTAINER_DLL_remove (monitor_head,
356                                    monitor_tail,
357                                    zm);
358       if (GNUNET_SCHEDULER_NO_TASK != zm->task)
359       {
360         GNUNET_SCHEDULER_cancel (zm->task);
361         zm->task = GNUNET_SCHEDULER_NO_TASK;
362       }
363       GNUNET_free (zm);
364       break;
365     }
366   }
367   for (cop = cop_head; NULL != cop; cop = cop->next)
368     if (client == cop->client)
369       cop->client = NULL;
370 }
371
372
373 /**
374  * Add a client to our list of active clients, if it is not yet
375  * in there.
376  *
377  * @param client client to add
378  * @return internal namestore client structure for this client
379  */
380 static struct NamestoreClient *
381 client_lookup (struct GNUNET_SERVER_Client *client)
382 {
383   struct NamestoreClient *nc;
384
385   nc = GNUNET_SERVER_client_get_user_context (client, struct NamestoreClient);
386   if (NULL != nc)
387     return nc;
388   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
389               "Client %p connected\n",
390               client);
391   nc = GNUNET_new (struct NamestoreClient);
392   nc->client = client;
393   GNUNET_SERVER_notification_context_add (snc, client);
394   GNUNET_CONTAINER_DLL_insert (client_head, client_tail, nc);
395   GNUNET_SERVER_client_set_user_context (client, nc);
396   return nc;
397 }
398
399
400 static void lookup_nick_it (void *cls,
401      const struct GNUNET_CRYPTO_EcdsaPrivateKey *private_key,
402      const char *label,
403      unsigned int rd_count,
404      const struct GNUNET_GNSRECORD_Data *rd)
405 {
406   struct GNUNET_GNSRECORD_Data **res = (cls);
407
408   int c;
409   if (0 != strcmp (label, GNUNET_GNS_MASTERZONE_STR))
410   {
411     GNUNET_break (0);
412     return;
413   }
414   for (c = 0; c < rd_count; c++)
415   {
416     if (GNUNET_GNSRECORD_TYPE_NICK == rd[c].record_type)
417     {
418       (*res) = GNUNET_malloc (rd[c].data_size + sizeof (struct GNUNET_GNSRECORD_Data));
419       (*res)->data = &(*res)[1];
420       memcpy ((char *)(*res)->data, rd[c].data, rd[c].data_size);
421       (*res)->data_size = rd[c].data_size;
422       (*res)->expiration_time = rd[c].expiration_time;
423       (*res)->flags = rd[c].flags;
424       (*res)->record_type = GNUNET_GNSRECORD_TYPE_NICK;
425       return;
426     }
427   }
428   (*res) = NULL;
429 }
430
431
432 static struct GNUNET_GNSRECORD_Data *
433 get_nick_record (const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone)
434 {
435   struct GNUNET_CRYPTO_EcdsaPublicKey pub;
436   struct GNUNET_GNSRECORD_Data *nick;
437   int res;
438
439   res = GSN_database->lookup_records (GSN_database->cls, zone,
440       GNUNET_GNS_MASTERZONE_STR, &lookup_nick_it, &nick);
441
442   if ((NULL == nick) || (GNUNET_OK != res))
443   {
444     GNUNET_CRYPTO_ecdsa_key_get_public (zone, &pub);
445     GNUNET_log(GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK, "No nick name set for zone `%s'\n",
446         GNUNET_CRYPTO_ecdsa_public_key_to_string (&pub));
447     return NULL;
448   }
449
450   return nick;
451 }
452
453
454 static void merge_records (unsigned int rdc1,
455                            const struct GNUNET_GNSRECORD_Data *rd1,
456                            unsigned int rdc2,
457                            const struct GNUNET_GNSRECORD_Data *rd2,
458                            unsigned int *rdc_res,
459                            struct GNUNET_GNSRECORD_Data **rd_res)
460 {
461   int c;
462   size_t req;
463   char *data;
464   int record_offset;
465   size_t data_offset;
466   (*rdc_res) = rdc1 + rdc2;
467
468   if (0 == rdc1 + rdc2)
469   {
470     (*rd_res) = NULL;
471     return;
472   }
473
474   req = 0;
475   for (c=0; c< rdc1; c++)
476     req += sizeof (struct GNUNET_GNSRECORD_Data) + rd1[c].data_size;
477   for (c=0; c< rdc2; c++)
478     req += sizeof (struct GNUNET_GNSRECORD_Data) + rd2[c].data_size;
479   (*rd_res) = GNUNET_malloc (req);
480   data = (char *) &(*rd_res)[rdc1 + rdc2];
481   data_offset = 0;
482
483   for (c=0; c< rdc1; c++)
484   {
485     (*rd_res)[c] = rd1[c];
486     (*rd_res)[c].data = (void *) &data[data_offset];
487     memcpy ((void *) (*rd_res)[c].data, rd1[c].data, rd1[c].data_size);
488     data_offset += (*rd_res)[c].data_size;
489   }
490   record_offset = rdc1;
491   for (c=0; c< rdc2; c++)
492   {
493     (*rd_res)[c+record_offset] = rd2[c];
494     (*rd_res)[c+record_offset].data = (void *) &data[data_offset];
495     memcpy ((void *) (*rd_res)[c+record_offset].data, rd2[c].data, rd2[c].data_size);
496     data_offset += (*rd_res)[c+record_offset].data_size;
497   }
498   GNUNET_assert (req == (sizeof (struct GNUNET_GNSRECORD_Data)) * (*rdc_res) + data_offset);
499 }
500
501
502
503 /**
504  * Generate a 'struct LookupNameResponseMessage' and send it to the
505  * given client using the given notification context.
506  *
507  * @param nc notification context to use
508  * @param client client to unicast to
509  * @param request_id request ID to use
510  * @param zone_key zone key of the zone
511  * @param name name
512  * @param rd_count number of records in @a rd
513  * @param rd array of records
514  */
515 static void
516 send_lookup_response (struct GNUNET_SERVER_NotificationContext *nc,
517                       struct GNUNET_SERVER_Client *client,
518                       uint32_t request_id,
519                       const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
520                       const char *name,
521                       unsigned int rd_count,
522                       const struct GNUNET_GNSRECORD_Data *rd)
523 {
524   struct RecordResultMessage *zir_msg;
525   struct GNUNET_GNSRECORD_Data *nick;
526   struct GNUNET_GNSRECORD_Data *res;
527   unsigned int res_count;
528   size_t name_len;
529   size_t rd_ser_len;
530   size_t msg_size;
531   char *name_tmp;
532   char *rd_ser;
533
534   nick = get_nick_record (zone_key);
535   if ((NULL != nick) && (0 != strcmp(name, GNUNET_GNS_MASTERZONE_STR)))
536   {
537     nick->flags = (nick->flags | GNUNET_GNSRECORD_RF_PRIVATE) ^ GNUNET_GNSRECORD_RF_PRIVATE;
538     merge_records (rd_count,rd, 1, nick, &res_count, &res);
539     //fprintf (stderr, "Merging %u records for `%s' with NICK records\n",rd_count, name);
540     GNUNET_free (nick);
541   }
542   else
543   {
544     res_count = rd_count;
545     res = (struct GNUNET_GNSRECORD_Data *) rd;
546     //fprintf (stderr, "Not merging %u records for `%s' with NICK records\n",rd_count, name);
547   }
548
549   name_len = strlen (name) + 1;
550   rd_ser_len = GNUNET_GNSRECORD_records_get_size (res_count, res);
551   msg_size = sizeof (struct RecordResultMessage) + name_len + rd_ser_len;
552   (void) client_lookup (client);
553   zir_msg = GNUNET_malloc (msg_size);
554   zir_msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT);
555   zir_msg->gns_header.header.size = htons (msg_size);
556   zir_msg->gns_header.r_id = htonl (request_id);
557   zir_msg->name_len = htons (name_len);
558   zir_msg->rd_count = htons (res_count);
559   zir_msg->rd_len = htons (rd_ser_len);
560   zir_msg->private_key = *zone_key;
561   name_tmp = (char *) &zir_msg[1];
562   memcpy (name_tmp, name, name_len);
563   rd_ser = &name_tmp[name_len];
564   GNUNET_GNSRECORD_records_serialize (res_count, res, rd_ser_len, rd_ser);
565   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
566               "Sending `%s' message with %u records and size %u\n",
567               "RECORD_RESULT",
568               res_count,
569               msg_size);
570   GNUNET_SERVER_notification_context_unicast (nc,
571                                               client,
572                                               &zir_msg->gns_header.header,
573                                               GNUNET_NO);
574   if (rd != res)
575     GNUNET_free (res);
576   GNUNET_free (zir_msg);
577 }
578
579
580 /**
581  * Send response to the store request to the client.
582  *
583  * @param client client to talk to
584  * @param res status of the operation
585  * @param rid client's request ID
586  */
587 static void
588 send_store_response (struct GNUNET_SERVER_Client *client,
589                      int res,
590                      uint32_t rid)
591 {
592   struct RecordStoreResponseMessage rcr_msg;
593
594   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
595               "Sending `%s' message\n",
596               "RECORD_STORE_RESPONSE");
597   rcr_msg.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE_RESPONSE);
598   rcr_msg.gns_header.header.size = htons (sizeof (struct RecordStoreResponseMessage));
599   rcr_msg.gns_header.r_id = htonl (rid);
600   rcr_msg.op_result = htonl (res);
601   GNUNET_SERVER_notification_context_unicast (snc, client,
602                                               &rcr_msg.gns_header.header,
603                                               GNUNET_NO);
604 }
605
606
607 /**
608  * Cache operation complete, clean up.
609  *
610  * @param cls the `struct CacheOperation`
611  * @param success success
612  * @param emsg error messages
613  */
614 static void
615 finish_cache_operation (void *cls,
616                         int32_t success,
617                         const char *emsg)
618 {
619   struct CacheOperation *cop = cls;
620
621   if (NULL != emsg)
622     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
623                 _("Failed to replicate block in namecache: %s\n"),
624                 emsg);
625   else
626     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
627                 "CACHE operation completed\n");
628   GNUNET_CONTAINER_DLL_remove (cop_head,
629                                cop_tail,
630                                cop);
631   if (NULL != cop->client)
632     send_store_response (cop->client,
633                          success,
634                          cop->rid);
635   GNUNET_free (cop);
636 }
637
638
639 /**
640  * We just touched the plaintext information about a name in our zone;
641  * refresh the corresponding (encrypted) block in the namecache.
642  *
643  * @param client client responsible for the request
644  * @param rid request ID of the client
645  * @param zone_key private key of the zone
646  * @param name label for the records
647  * @param rd_count number of records
648  * @param rd records stored under the given @a name
649  */
650 static void
651 refresh_block (struct GNUNET_SERVER_Client *client,
652                uint32_t rid,
653                const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
654                const char *name,
655                unsigned int rd_count,
656                const struct GNUNET_GNSRECORD_Data *rd)
657 {
658   struct GNUNET_GNSRECORD_Block *block;
659   struct CacheOperation *cop;
660   struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
661
662   if (0 == rd_count)
663     block = GNUNET_GNSRECORD_block_create (zone_key,
664                                            GNUNET_TIME_UNIT_ZERO_ABS,
665                                            name,
666                                            rd, rd_count);
667   else
668     block = GNUNET_GNSRECORD_block_create (zone_key,
669                                            GNUNET_GNSRECORD_record_get_expiration_time (rd_count,
670                                                                                         rd),
671                                            name,
672                                            rd, rd_count);
673   GNUNET_assert (NULL != block);
674   GNUNET_CRYPTO_ecdsa_key_get_public (zone_key,
675                                       &pkey);
676   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
677               "Caching block for label `%s' in zone `%s' in namecache\n",
678               name,
679               GNUNET_GNSRECORD_z2s (&pkey));
680   cop = GNUNET_new (struct CacheOperation);
681   cop->client = client;
682   cop->rid = rid;
683   GNUNET_CONTAINER_DLL_insert (cop_head,
684                                cop_tail,
685                                cop);
686   cop->qe = GNUNET_NAMECACHE_block_cache (namecache,
687                                           block,
688                                           &finish_cache_operation,
689                                           cop);
690   GNUNET_free (block);
691 }
692
693
694 struct RecordLookupContext
695 {
696   const char *label;
697
698   int found;
699
700   unsigned int res_rd_count;
701
702   size_t rd_ser_len;
703
704   char *res_rd;
705
706   struct GNUNET_GNSRECORD_Data *nick;
707 };
708
709
710
711 static void
712 lookup_it (void *cls, const struct GNUNET_CRYPTO_EcdsaPrivateKey *private_key,
713     const char *label, unsigned int rd_count,
714     const struct GNUNET_GNSRECORD_Data *rd)
715 {
716   struct RecordLookupContext *rlc = cls;
717   struct GNUNET_GNSRECORD_Data *rd_res;
718   unsigned int rdc_res;
719
720   if (0 == strcmp (label, rlc->label))
721   {
722     rlc->found = GNUNET_YES;
723     if (0 != rd_count)
724     {
725       if ((NULL != rlc->nick) && (0 != strcmp(label, GNUNET_GNS_MASTERZONE_STR)))
726       {
727         /* Merge */
728         rd_res = NULL;
729         rdc_res = 0;
730         rlc->nick->flags = (rlc->nick->flags | GNUNET_GNSRECORD_RF_PRIVATE) ^ GNUNET_GNSRECORD_RF_PRIVATE;
731         merge_records (rd_count, rd,
732                        1, rlc->nick,
733                        &rdc_res, &rd_res);
734
735         rlc->rd_ser_len = GNUNET_GNSRECORD_records_get_size (rdc_res, rd_res);
736         rlc->res_rd_count = rdc_res;
737         rlc->res_rd = GNUNET_malloc (rlc->rd_ser_len);
738         GNUNET_GNSRECORD_records_serialize (rdc_res, rd_res, rlc->rd_ser_len , rlc->res_rd);
739
740         GNUNET_free  (rd_res);
741         GNUNET_free  (rlc->nick);
742         rlc->nick = NULL;
743       }
744       else
745       {
746         rlc->rd_ser_len = GNUNET_GNSRECORD_records_get_size (rd_count, rd);
747         rlc->res_rd_count = rd_count;
748         rlc->res_rd = GNUNET_malloc (rlc->rd_ser_len);
749         GNUNET_GNSRECORD_records_serialize (rd_count, rd, rlc->rd_ser_len , rlc->res_rd);
750       }
751     }
752     else
753     {
754       rlc->rd_ser_len = 0;
755       rlc->res_rd_count = 0;
756       rlc->res_rd = NULL;
757     }
758   }
759 }
760
761
762
763
764
765 /**
766  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_LOOKUP message
767  *
768  * @param cls unused
769  * @param client client sending the message
770  * @param message message of type 'struct RecordCreateMessage'
771  */
772 static void
773 handle_record_lookup (void *cls,
774                      struct GNUNET_SERVER_Client *client,
775                      const struct GNUNET_MessageHeader *message)
776 {
777   const struct LabelLookupMessage *ll_msg;
778   struct LabelLookupResponseMessage *llr_msg;
779   struct RecordLookupContext rlc;
780   const char *name_tmp;
781   char *res_name;
782   uint32_t name_len;
783   size_t src_size;
784   size_t res_size;
785   int res;
786
787   if (ntohs (message->size) < sizeof (struct LabelLookupMessage))
788   {
789     GNUNET_break (0);
790     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
791     return;
792   }
793
794   ll_msg = (const struct LabelLookupMessage *) message;
795   name_len = ntohl (ll_msg->label_len);
796   src_size = ntohs (message->size);
797
798   if (name_len !=  src_size - sizeof (struct LabelLookupMessage))
799   {
800     GNUNET_break (0);
801     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
802     return;
803   }
804
805   name_tmp = (const char *) &ll_msg[1];
806   if ('\0' != name_tmp[name_len -1])
807   {
808     GNUNET_break (0);
809     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
810     return;
811   }
812
813   GNUNET_SERVER_receive_done (client, GNUNET_OK);
814   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
815               "Received `%s' message for name `%s'\n",
816               "NAMESTORE_RECORD_LOOKUP", name_tmp);
817
818   if (NULL == (client_lookup (client)))
819   {
820     GNUNET_break (0);
821     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
822     return;
823   }
824
825   rlc.label = name_tmp;
826   rlc.found = GNUNET_NO;
827   rlc.res_rd_count = 0;
828   rlc.res_rd = NULL;
829   rlc.rd_ser_len = 0;
830   rlc.nick = get_nick_record (&ll_msg->zone);
831
832   res = GSN_database->lookup_records (GSN_database->cls,
833         &ll_msg->zone, name_tmp, &lookup_it, &rlc);
834
835   res_size = sizeof (struct LabelLookupResponseMessage) + name_len + rlc.rd_ser_len;
836   llr_msg = GNUNET_malloc (res_size);
837   llr_msg->gns_header.header.size = htons (res_size);
838   llr_msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_LOOKUP_RESPONSE);
839   llr_msg->gns_header.r_id = ll_msg->gns_header.r_id;
840   llr_msg->private_key = ll_msg->zone;
841   llr_msg->name_len = htons (name_len);
842   llr_msg->rd_count = htons (rlc.res_rd_count);
843   llr_msg->rd_len = htons (rlc.rd_ser_len);
844   res_name = (char *) &llr_msg[1];
845   if  ((GNUNET_YES == rlc.found) && (GNUNET_OK == res))
846     llr_msg->found = ntohs (GNUNET_YES);
847   else
848     llr_msg->found = ntohs (GNUNET_NO);
849   memcpy (&llr_msg[1], name_tmp, name_len);
850   memcpy (&res_name[name_len], rlc.res_rd, rlc.rd_ser_len);
851
852   GNUNET_SERVER_notification_context_unicast (snc, client, &llr_msg->gns_header.header,
853       GNUNET_NO);
854
855   GNUNET_free_non_null (rlc.res_rd);
856   GNUNET_free (llr_msg);
857 }
858
859
860 /**
861  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE message
862  *
863  * @param cls unused
864  * @param client client sending the message
865  * @param message message of type 'struct RecordCreateMessage'
866  */
867 static void
868 handle_record_store (void *cls,
869                      struct GNUNET_SERVER_Client *client,
870                      const struct GNUNET_MessageHeader *message)
871 {
872   const struct RecordStoreMessage *rp_msg;
873   size_t name_len;
874   size_t msg_size;
875   size_t msg_size_exp;
876   size_t rd_ser_len;
877   uint32_t rid;
878   const char *name_tmp;
879   char *conv_name;
880   const char *rd_ser;
881   unsigned int rd_count;
882   int res;
883   struct GNUNET_CRYPTO_EcdsaPublicKey pubkey;
884   struct ZoneMonitor *zm;
885
886   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
887               "Received `%s' message\n",
888               "NAMESTORE_RECORD_STORE");
889   if (ntohs (message->size) < sizeof (struct RecordStoreMessage))
890   {
891     GNUNET_break (0);
892     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
893     return;
894   }
895   rp_msg = (const struct RecordStoreMessage *) message;
896   rid = ntohl (rp_msg->gns_header.r_id);
897   name_len = ntohs (rp_msg->name_len);
898   msg_size = ntohs (message->size);
899   rd_count = ntohs (rp_msg->rd_count);
900   rd_ser_len = ntohs (rp_msg->rd_len);
901   GNUNET_break (0 == ntohs (rp_msg->reserved));
902   msg_size_exp = sizeof (struct RecordStoreMessage) + name_len + rd_ser_len;
903   if (msg_size != msg_size_exp)
904   {
905     GNUNET_break (0);
906     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
907     return;
908   }
909   if ((0 == name_len) || (name_len > MAX_NAME_LEN))
910   {
911     GNUNET_break (0);
912     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
913     return;
914   }
915   name_tmp = (const char *) &rp_msg[1];
916   rd_ser = &name_tmp[name_len];
917   if ('\0' != name_tmp[name_len -1])
918   {
919     GNUNET_break (0);
920     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
921     return;
922   }
923   (void) client_lookup (client);
924   {
925     struct GNUNET_GNSRECORD_Data rd[rd_count];
926
927     if (GNUNET_OK !=
928         GNUNET_GNSRECORD_records_deserialize (rd_ser_len, rd_ser, rd_count, rd))
929     {
930       GNUNET_break (0);
931       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
932       return;
933     }
934
935     /* Extracting and converting private key */
936     GNUNET_CRYPTO_ecdsa_key_get_public (&rp_msg->private_key,
937                                       &pubkey);
938     conv_name = GNUNET_GNSRECORD_string_to_lowercase (name_tmp);
939     if (NULL == conv_name)
940     {
941       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
942                   "Error converting name `%s'\n", name_tmp);
943       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
944       return;
945     }
946     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
947                 "Creating %u records for name `%s' in zone `%s'\n",
948                 (unsigned int) rd_count,
949                 conv_name,
950                 GNUNET_GNSRECORD_z2s (&pubkey));
951
952     if ( (0 == rd_count) &&
953          (GNUNET_NO ==
954           GSN_database->iterate_records (GSN_database->cls,
955                                          &rp_msg->private_key, 0, NULL, 0)) )
956     {
957       /* This name does not exist, so cannot be removed */
958       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
959                   "Name `%s' does not exist, no deletion required\n",
960                   conv_name);
961       res = GNUNET_NO;
962     }
963     else
964     {
965       res = GSN_database->store_records (GSN_database->cls,
966                                          &rp_msg->private_key,
967                                          conv_name,
968                                          rd_count, rd);
969       if (GNUNET_OK == res)
970       {
971         for (zm = monitor_head; NULL != zm; zm = zm->next)
972         {
973           if ( (0 == memcmp (&rp_msg->private_key, &zm->zone,
974                              sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey))) ||
975                (0 == memcmp (&zm->zone,
976                              &zero,
977                              sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey))) )
978           {
979             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
980                         "Notifying monitor about changes under label `%s'\n",
981                         conv_name);
982             send_lookup_response (monitor_nc,
983                                   zm->nc->client,
984                                   0,
985                                   &rp_msg->private_key,
986                                   conv_name,
987                                   rd_count, rd);
988           }
989           else
990             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
991                         "Monitor is for another zone\n");
992         }
993         if (NULL == monitor_head)
994           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
995                       "No monitors active\n");
996       }
997       else
998       {
999         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1000                     "Error storing record: %d\n",
1001                     res);
1002       }
1003     }
1004     if (GNUNET_OK == res)
1005     {
1006       refresh_block (client, rid,
1007                      &rp_msg->private_key,
1008                      conv_name,
1009                      rd_count, rd);
1010       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1011       GNUNET_free (conv_name);
1012       return;
1013     }
1014     GNUNET_free (conv_name);
1015   }
1016   send_store_response (client, res, rid);
1017   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1018 }
1019
1020
1021 /**
1022  * Context for record remove operations passed from #handle_zone_to_name to
1023  * #handle_zone_to_name_it as closure
1024  */
1025 struct ZoneToNameCtx
1026 {
1027   /**
1028    * Namestore client
1029    */
1030   struct NamestoreClient *nc;
1031
1032   /**
1033    * Request id (to be used in the response to the client).
1034    */
1035   uint32_t rid;
1036
1037   /**
1038    * Set to #GNUNET_OK on success, #GNUNET_SYSERR on error.  Note that
1039    * not finding a name for the zone still counts as a 'success' here,
1040    * as this field is about the success of executing the IPC protocol.
1041    */
1042   int success;
1043 };
1044
1045
1046 /**
1047  * Zone to name iterator
1048  *
1049  * @param cls struct ZoneToNameCtx *
1050  * @param zone_key the zone key
1051  * @param name name
1052  * @param rd_count number of records in @a rd
1053  * @param rd record data
1054  */
1055 static void
1056 handle_zone_to_name_it (void *cls,
1057                         const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
1058                         const char *name,
1059                         unsigned int rd_count,
1060                         const struct GNUNET_GNSRECORD_Data *rd)
1061 {
1062   struct ZoneToNameCtx *ztn_ctx = cls;
1063   struct ZoneToNameResponseMessage *ztnr_msg;
1064   int16_t res;
1065   size_t name_len;
1066   size_t rd_ser_len;
1067   size_t msg_size;
1068   char *name_tmp;
1069   char *rd_tmp;
1070
1071   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1072               "Found result for zone-to-name lookup: `%s'\n",
1073               name);
1074   res = GNUNET_YES;
1075   name_len = (NULL == name) ? 0 : strlen (name) + 1;
1076   rd_ser_len = GNUNET_GNSRECORD_records_get_size (rd_count, rd);
1077   msg_size = sizeof (struct ZoneToNameResponseMessage) + name_len + rd_ser_len;
1078   if (msg_size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1079   {
1080     GNUNET_break (0);
1081     ztn_ctx->success = GNUNET_SYSERR;
1082     return;
1083   }
1084   ztnr_msg = GNUNET_malloc (msg_size);
1085   ztnr_msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME_RESPONSE);
1086   ztnr_msg->gns_header.header.size = htons (msg_size);
1087   ztnr_msg->gns_header.r_id = htonl (ztn_ctx->rid);
1088   ztnr_msg->res = htons (res);
1089   ztnr_msg->rd_len = htons (rd_ser_len);
1090   ztnr_msg->rd_count = htons (rd_count);
1091   ztnr_msg->name_len = htons (name_len);
1092   ztnr_msg->zone = *zone_key;
1093   name_tmp = (char *) &ztnr_msg[1];
1094   if (NULL != name)
1095     memcpy (name_tmp, name, name_len);
1096   rd_tmp = &name_tmp[name_len];
1097   GNUNET_GNSRECORD_records_serialize (rd_count, rd, rd_ser_len, rd_tmp);
1098   ztn_ctx->success = GNUNET_OK;
1099   GNUNET_SERVER_notification_context_unicast (snc, ztn_ctx->nc->client,
1100                                               &ztnr_msg->gns_header.header,
1101                                               GNUNET_NO);
1102   GNUNET_free (ztnr_msg);
1103 }
1104
1105
1106 /**
1107  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME message
1108  *
1109  * @param cls unused
1110  * @param client client sending the message
1111  * @param message message of type 'struct ZoneToNameMessage'
1112  */
1113 static void
1114 handle_zone_to_name (void *cls,
1115                      struct GNUNET_SERVER_Client *client,
1116                      const struct GNUNET_MessageHeader *message)
1117 {
1118   struct NamestoreClient *nc;
1119   const struct ZoneToNameMessage *ztn_msg;
1120   struct ZoneToNameCtx ztn_ctx;
1121   struct ZoneToNameResponseMessage ztnr_msg;
1122
1123   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1124               "Received `%s' message\n",
1125               "ZONE_TO_NAME");
1126   ztn_msg = (const struct ZoneToNameMessage *) message;
1127   nc = client_lookup (client);
1128   ztn_ctx.rid = ntohl (ztn_msg->gns_header.r_id);
1129   ztn_ctx.nc = nc;
1130   ztn_ctx.success = GNUNET_NO;
1131   if (GNUNET_SYSERR ==
1132       GSN_database->zone_to_name (GSN_database->cls,
1133                                   &ztn_msg->zone,
1134                                   &ztn_msg->value_zone,
1135                                   &handle_zone_to_name_it, &ztn_ctx))
1136   {
1137     /* internal error, hang up instead of signalling something
1138        that might be wrong */
1139     GNUNET_break (0);
1140     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1141     return;
1142   }
1143   if (GNUNET_NO == ztn_ctx.success)
1144   {
1145     /* no result found, send empty response */
1146     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1147                 "Found no result for zone-to-name lookup.\n");
1148     memset (&ztnr_msg, 0, sizeof (ztnr_msg));
1149     ztnr_msg.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME_RESPONSE);
1150     ztnr_msg.gns_header.header.size = htons (sizeof (ztnr_msg));
1151     ztnr_msg.gns_header.r_id = ztn_msg->gns_header.r_id;
1152     ztnr_msg.res = htons (GNUNET_NO);
1153     GNUNET_SERVER_notification_context_unicast (snc,
1154                                                 client,
1155                                                 &ztnr_msg.gns_header.header,
1156                                                 GNUNET_NO);
1157   }
1158   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1159 }
1160
1161
1162 /**
1163  * Zone iteration processor result
1164  */
1165 enum ZoneIterationResult
1166 {
1167   /**
1168    * Iteration start.
1169    */
1170   IT_START = 0,
1171
1172   /**
1173    * Found records,
1174    * Continue to iterate with next iteration_next call
1175    */
1176   IT_SUCCESS_MORE_AVAILABLE = 1,
1177
1178   /**
1179    * Iteration complete
1180    */
1181   IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE = 2
1182 };
1183
1184
1185 /**
1186  * Context for record remove operations passed from
1187  * #run_zone_iteration_round to #zone_iterate_proc as closure
1188  */
1189 struct ZoneIterationProcResult
1190 {
1191   /**
1192    * The zone iteration handle
1193    */
1194   struct ZoneIteration *zi;
1195
1196   /**
1197    * Iteration result: iteration done?
1198    * #IT_SUCCESS_MORE_AVAILABLE:  if there may be more results overall but
1199    * we got one for now and have sent it to the client
1200    * #IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE: if there are no further results,
1201    * #IT_START: if we are still trying to find a result.
1202    */
1203   int res_iteration_finished;
1204
1205 };
1206
1207
1208 /**
1209  * Process results for zone iteration from database
1210  *
1211  * @param cls struct ZoneIterationProcResult *proc
1212  * @param zone_key the zone key
1213  * @param name name
1214  * @param rd_count number of records for this name
1215  * @param rd record data
1216  */
1217 static void
1218 zone_iterate_proc (void *cls,
1219                        const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
1220                        const char *name,
1221                        unsigned int rd_count,
1222                        const struct GNUNET_GNSRECORD_Data *rd)
1223 {
1224   struct ZoneIterationProcResult *proc = cls;
1225   unsigned int i;
1226   int do_refresh_block;
1227
1228   if ((NULL == zone_key) && (NULL == name))
1229   {
1230     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1231                 "Iteration done\n");
1232     proc->res_iteration_finished = IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE;
1233     return;
1234   }
1235   if ((NULL == zone_key) || (NULL == name))
1236   {
1237     /* what is this!? should never happen */
1238     proc->res_iteration_finished = IT_START;
1239     GNUNET_break (0);
1240     return;
1241   }
1242   proc->res_iteration_finished = IT_SUCCESS_MORE_AVAILABLE;
1243   send_lookup_response (snc,
1244                         proc->zi->client->client,
1245                         proc->zi->request_id,
1246                         zone_key,
1247                         name,
1248                         rd_count,
1249                         rd);
1250   do_refresh_block = GNUNET_NO;
1251   for (i=0;i<rd_count;i++)
1252     if(  (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION)) &&
1253          (0 == (rd[i].flags & GNUNET_GNSRECORD_RF_PENDING)) )
1254     {
1255       do_refresh_block = GNUNET_YES;
1256       break;
1257     }
1258   if (GNUNET_YES == do_refresh_block)
1259     refresh_block (NULL, 0,
1260                    zone_key,
1261                    name,
1262                    rd_count,
1263                    rd);
1264
1265 }
1266
1267
1268 /**
1269  * Perform the next round of the zone iteration.
1270  *
1271  * @param zi zone iterator to process
1272  */
1273 static void
1274 run_zone_iteration_round (struct ZoneIteration *zi)
1275 {
1276   struct ZoneIterationProcResult proc;
1277   struct RecordResultMessage rrm;
1278   int ret;
1279
1280   memset (&proc, 0, sizeof (proc));
1281   proc.zi = zi;
1282   proc.res_iteration_finished = IT_START;
1283   while (IT_START == proc.res_iteration_finished)
1284   {
1285     if (GNUNET_SYSERR ==
1286         (ret = GSN_database->iterate_records (GSN_database->cls,
1287                                               (0 == memcmp (&zi->zone, &zero, sizeof (zero)))
1288                                               ? NULL
1289                                               : &zi->zone,
1290                                               zi->offset,
1291                                               &zone_iterate_proc, &proc)))
1292     {
1293       GNUNET_break (0);
1294       break;
1295     }
1296     if (GNUNET_NO == ret)
1297       proc.res_iteration_finished = IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE;
1298     zi->offset++;
1299   }
1300   if (IT_SUCCESS_MORE_AVAILABLE == proc.res_iteration_finished)
1301   {
1302     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1303                 "More results available\n");
1304     return; /* more results later */
1305   }
1306   /* send empty response to indicate end of list */
1307   memset (&rrm, 0, sizeof (rrm));
1308   rrm.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT);
1309   rrm.gns_header.header.size = htons (sizeof (rrm));
1310   rrm.gns_header.r_id = htonl (zi->request_id);
1311   GNUNET_SERVER_notification_context_unicast (snc,
1312                                               zi->client->client,
1313                                               &rrm.gns_header.header,
1314                                               GNUNET_NO);
1315   GNUNET_CONTAINER_DLL_remove (zi->client->op_head,
1316                                zi->client->op_tail,
1317                                zi);
1318   GNUNET_free (zi);
1319 }
1320
1321
1322 /**
1323  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_START message
1324  *
1325  * @param cls unused
1326  * @param client the client sending the message
1327  * @param message message of type 'struct ZoneIterationStartMessage'
1328  */
1329 static void
1330 handle_iteration_start (void *cls,
1331                         struct GNUNET_SERVER_Client *client,
1332                         const struct GNUNET_MessageHeader *message)
1333 {
1334   const struct ZoneIterationStartMessage *zis_msg;
1335   struct NamestoreClient *nc;
1336   struct ZoneIteration *zi;
1337
1338   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "ZONE_ITERATION_START");
1339   if (NULL == (nc = client_lookup (client)))
1340   {
1341     GNUNET_break (0);
1342     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1343     return;
1344   }
1345   zis_msg = (const struct ZoneIterationStartMessage *) message;
1346   zi = GNUNET_new (struct ZoneIteration);
1347   zi->request_id = ntohl (zis_msg->gns_header.r_id);
1348   zi->offset = 0;
1349   zi->client = nc;
1350   zi->zone = zis_msg->zone;
1351
1352
1353   GNUNET_CONTAINER_DLL_insert (nc->op_head, nc->op_tail, zi);
1354   run_zone_iteration_round (zi);
1355   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1356 }
1357
1358
1359 /**
1360  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_STOP message
1361  *
1362  * @param cls unused
1363  * @param client GNUNET_SERVER_Client sending the message
1364  * @param message message of type 'struct ZoneIterationStopMessage'
1365  */
1366 static void
1367 handle_iteration_stop (void *cls,
1368                        struct GNUNET_SERVER_Client *client,
1369                        const struct GNUNET_MessageHeader *message)
1370 {
1371   struct NamestoreClient *nc;
1372   struct ZoneIteration *zi;
1373   const struct ZoneIterationStopMessage *zis_msg;
1374   uint32_t rid;
1375
1376   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1377               "Received `%s' message\n",
1378               "ZONE_ITERATION_STOP");
1379   if (NULL == (nc = client_lookup(client)))
1380   {
1381     GNUNET_break (0);
1382     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1383     return;
1384   }
1385   zis_msg = (const struct ZoneIterationStopMessage *) message;
1386   rid = ntohl (zis_msg->gns_header.r_id);
1387   for (zi = nc->op_head; NULL != zi; zi = zi->next)
1388     if (zi->request_id == rid)
1389       break;
1390   if (NULL == zi)
1391   {
1392     GNUNET_break (0);
1393     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1394     return;
1395   }
1396   GNUNET_CONTAINER_DLL_remove (nc->op_head, nc->op_tail, zi);
1397   GNUNET_free (zi);
1398   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1399 }
1400
1401
1402 /**
1403  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_NEXT message
1404  *
1405  * @param cls unused
1406  * @param client GNUNET_SERVER_Client sending the message
1407  * @param message message of type 'struct ZoneIterationNextMessage'
1408  */
1409 static void
1410 handle_iteration_next (void *cls,
1411                        struct GNUNET_SERVER_Client *client,
1412                        const struct GNUNET_MessageHeader *message)
1413 {
1414   struct NamestoreClient *nc;
1415   struct ZoneIteration *zi;
1416   const struct ZoneIterationNextMessage *zis_msg;
1417   uint32_t rid;
1418
1419   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1420               "Received `%s' message\n",
1421               "ZONE_ITERATION_NEXT");
1422   if (NULL == (nc = client_lookup(client)))
1423   {
1424     GNUNET_break (0);
1425     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1426     return;
1427   }
1428   zis_msg = (const struct ZoneIterationNextMessage *) message;
1429   rid = ntohl (zis_msg->gns_header.r_id);
1430   for (zi = nc->op_head; NULL != zi; zi = zi->next)
1431     if (zi->request_id == rid)
1432       break;
1433   if (NULL == zi)
1434   {
1435     GNUNET_break (0);
1436     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1437     return;
1438   }
1439   run_zone_iteration_round (zi);
1440   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1441 }
1442
1443
1444 /**
1445  * Send 'sync' message to zone monitor, we're now in sync.
1446  *
1447  * @param zm monitor that is now in sync
1448  */
1449 static void
1450 monitor_sync (struct ZoneMonitor *zm)
1451 {
1452   struct GNUNET_MessageHeader sync;
1453
1454   sync.size = htons (sizeof (struct GNUNET_MessageHeader));
1455   sync.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_SYNC);
1456   GNUNET_SERVER_notification_context_unicast (monitor_nc,
1457                                               zm->nc->client,
1458                                               &sync,
1459                                               GNUNET_NO);
1460 }
1461
1462
1463 /**
1464  * Obtain the next datum during the zone monitor's zone intiial iteration.
1465  *
1466  * @param cls zone monitor that does its initial iteration
1467  * @param tc scheduler context
1468  */
1469 static void
1470 monitor_next (void *cls,
1471               const struct GNUNET_SCHEDULER_TaskContext *tc);
1472
1473
1474 /**
1475  * A #GNUNET_NAMESTORE_RecordIterator for monitors.
1476  *
1477  * @param cls a 'struct ZoneMonitor *' with information about the monitor
1478  * @param zone_key zone key of the zone
1479  * @param name name
1480  * @param rd_count number of records in @a rd
1481  * @param rd array of records
1482  */
1483 static void
1484 monitor_iterate_cb (void *cls,
1485                     const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
1486                     const char *name,
1487                     unsigned int rd_count,
1488                     const struct GNUNET_GNSRECORD_Data *rd)
1489 {
1490   struct ZoneMonitor *zm = cls;
1491
1492   if (NULL == name)
1493   {
1494     /* finished with iteration */
1495     monitor_sync (zm);
1496     return;
1497   }
1498   send_lookup_response (monitor_nc,
1499                         zm->nc->client,
1500                         0,
1501                         zone_key,
1502                         name,
1503                         rd_count,
1504                         rd);
1505   zm->task = GNUNET_SCHEDULER_add_now (&monitor_next, zm);
1506 }
1507
1508
1509 /**
1510  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_START message
1511  *
1512  * @param cls unused
1513  * @param client the client sending the message
1514  * @param message message of type 'struct ZoneMonitorStartMessage'
1515  */
1516 static void
1517 handle_monitor_start (void *cls,
1518                       struct GNUNET_SERVER_Client *client,
1519                       const struct GNUNET_MessageHeader *message)
1520 {
1521   const struct ZoneMonitorStartMessage *zis_msg;
1522   struct ZoneMonitor *zm;
1523
1524   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1525               "Received `%s' message\n",
1526               "ZONE_MONITOR_START");
1527   zis_msg = (const struct ZoneMonitorStartMessage *) message;
1528   zm = GNUNET_new (struct ZoneMonitor);
1529   zm->offset = 0;
1530   zm->nc = client_lookup (client);
1531   zm->zone = zis_msg->zone;
1532   GNUNET_CONTAINER_DLL_insert (monitor_head, monitor_tail, zm);
1533   GNUNET_SERVER_client_mark_monitor (client);
1534   GNUNET_SERVER_disable_receive_done_warning (client);
1535   GNUNET_SERVER_notification_context_add (monitor_nc,
1536                                           client);
1537   if (GNUNET_YES == ntohl (zis_msg->iterate_first))
1538     zm->task = GNUNET_SCHEDULER_add_now (&monitor_next, zm);
1539   else
1540     monitor_sync (zm);
1541 }
1542
1543
1544 /**
1545  * Obtain the next datum during the zone monitor's zone intiial iteration.
1546  *
1547  * @param cls zone monitor that does its initial iteration
1548  * @param tc scheduler context
1549  */
1550 static void
1551 monitor_next (void *cls,
1552               const struct GNUNET_SCHEDULER_TaskContext *tc)
1553 {
1554   struct ZoneMonitor *zm = cls;
1555   int ret;
1556
1557   zm->task = GNUNET_SCHEDULER_NO_TASK;
1558   ret = GSN_database->iterate_records (GSN_database->cls,
1559                                        (0 == memcmp (&zm->zone, &zero, sizeof (zero)))
1560                                        ? NULL
1561                                        : &zm->zone,
1562                                        zm->offset++,
1563                                        &monitor_iterate_cb, zm);
1564   if (GNUNET_SYSERR == ret)
1565   {
1566     GNUNET_SERVER_client_disconnect (zm->nc->client);
1567     return;
1568   }
1569   if (GNUNET_NO == ret)
1570   {
1571     /* empty zone */
1572     monitor_sync (zm);
1573     return;
1574   }
1575 }
1576
1577
1578 /**
1579  * Process namestore requests.
1580  *
1581  * @param cls closure
1582  * @param server the initialized server
1583  * @param cfg configuration to use
1584  */
1585 static void
1586 run (void *cls, struct GNUNET_SERVER_Handle *server,
1587      const struct GNUNET_CONFIGURATION_Handle *cfg)
1588 {
1589   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1590     {&handle_record_store, NULL,
1591      GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE, 0},
1592     {&handle_record_lookup, NULL,
1593      GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_LOOKUP, 0},
1594     {&handle_zone_to_name, NULL,
1595      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME, sizeof (struct ZoneToNameMessage) },
1596     {&handle_iteration_start, NULL,
1597      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_START, sizeof (struct ZoneIterationStartMessage) },
1598     {&handle_iteration_next, NULL,
1599      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_NEXT, sizeof (struct ZoneIterationNextMessage) },
1600     {&handle_iteration_stop, NULL,
1601      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_STOP, sizeof (struct ZoneIterationStopMessage) },
1602     {&handle_monitor_start, NULL,
1603      GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_START, sizeof (struct ZoneMonitorStartMessage) },
1604     {NULL, NULL, 0, 0}
1605   };
1606   char *database;
1607
1608   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting namestore service\n");
1609   GSN_cfg = cfg;
1610   monitor_nc = GNUNET_SERVER_notification_context_create (server, 1);
1611   namecache = GNUNET_NAMECACHE_connect (cfg);
1612   /* Loading database plugin */
1613   if (GNUNET_OK !=
1614       GNUNET_CONFIGURATION_get_value_string (cfg, "namestore", "database",
1615                                              &database))
1616     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No database backend configured\n");
1617
1618   GNUNET_asprintf (&db_lib_name, "libgnunet_plugin_namestore_%s", database);
1619   GSN_database = GNUNET_PLUGIN_load (db_lib_name, (void *) GSN_cfg);
1620   GNUNET_free (database);
1621   if (NULL == GSN_database)
1622   {
1623     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1624                 "Could not load database backend `%s'\n",
1625                 db_lib_name);
1626     GNUNET_SCHEDULER_add_now (&cleanup_task, NULL);
1627     return;
1628   }
1629
1630   /* Configuring server handles */
1631   GNUNET_SERVER_add_handlers (server, handlers);
1632   snc = GNUNET_SERVER_notification_context_create (server, 16);
1633   GNUNET_SERVER_disconnect_notify (server,
1634                                    &client_disconnect_notification,
1635                                    NULL);
1636   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleanup_task,
1637                                 NULL);
1638 }
1639
1640
1641 /**
1642  * The main function for the template service.
1643  *
1644  * @param argc number of arguments from the command line
1645  * @param argv command line arguments
1646  * @return 0 ok, 1 on error
1647  */
1648 int
1649 main (int argc, char *const *argv)
1650 {
1651   return (GNUNET_OK ==
1652           GNUNET_SERVICE_run (argc, argv, "namestore",
1653                               GNUNET_SERVICE_OPTION_NONE, &run, NULL)) ? 0 : 1;
1654 }
1655
1656 /* end of gnunet-service-namestore.c */
1657