-namestore service builds again
[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_namestore_service.h"
31 #include "gnunet_namestore_plugin.h"
32 #include "gnunet_signatures.h"
33 #include "namestore.h"
34
35 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
36
37
38 /**
39  * A namestore client
40  */
41 struct NamestoreClient;
42
43
44 /**
45  * A namestore iteration operation.
46  */
47 struct ZoneIteration
48 {
49   /**
50    * Next element in the DLL
51    */
52   struct ZoneIteration *next;
53
54   /**
55    * Previous element in the DLL
56    */
57   struct ZoneIteration *prev;
58
59   /**
60    * Namestore client which intiated this zone iteration
61    */
62   struct NamestoreClient *client;
63
64   /**
65    * Key of the zone we are iterating over.
66    */
67   struct GNUNET_CRYPTO_EccPrivateKey zone;
68
69   /**
70    * The operation id fot the zone iteration in the response for the client
71    */
72   uint32_t request_id;
73
74   /**
75    * Offset of the zone iteration used to address next result of the zone
76    * iteration in the store
77    *
78    * Initialy set to 0 in handle_iteration_start
79    * Incremented with by every call to handle_iteration_next
80    */
81   uint32_t offset;
82
83 };
84
85
86 /**
87  * A namestore client
88  */
89 struct NamestoreClient
90 {
91   /**
92    * Next element in the DLL
93    */
94   struct NamestoreClient *next;
95
96   /**
97    * Previous element in the DLL
98    */
99   struct NamestoreClient *prev;
100
101   /**
102    * The client
103    */
104   struct GNUNET_SERVER_Client *client;
105
106   /**
107    * Head of the DLL of
108    * Zone iteration operations in progress initiated by this client
109    */
110   struct ZoneIteration *op_head;
111
112   /**
113    * Tail of the DLL of
114    * Zone iteration operations in progress initiated by this client
115    */
116   struct ZoneIteration *op_tail;
117 };
118
119
120 /**
121  * A namestore monitor.
122  */
123 struct ZoneMonitor
124 {
125   /**
126    * Next element in the DLL
127    */
128   struct ZoneMonitor *next;
129
130   /**
131    * Previous element in the DLL
132    */
133   struct ZoneMonitor *prev;
134
135   /**
136    * Namestore client which intiated this zone monitor
137    */
138   struct NamestoreClient *nc;
139
140   /**
141    * Private key of the zone.
142    */
143   struct GNUNET_CRYPTO_EccPrivateKey zone;
144
145   /**
146    * The operation id fot the zone iteration in the response for the client
147    */
148   uint32_t request_id;
149
150   /**
151    * Task active during initial iteration.
152    */
153   GNUNET_SCHEDULER_TaskIdentifier task;
154
155   /**
156    * Offset of the zone iteration used to address next result of the zone
157    * iteration in the store
158    *
159    * Initialy set to 0 in handle_iteration_start
160    * Incremented with by every call to handle_iteration_next
161    */
162   uint32_t offset;
163
164 };
165
166
167 /**
168  * Configuration handle.
169  */
170 static const struct GNUNET_CONFIGURATION_Handle *GSN_cfg;
171
172 /**
173  * Database handle
174  */
175 static struct GNUNET_NAMESTORE_PluginFunctions *GSN_database;
176
177 /**
178  * Name of the database plugin
179  */
180 static char *db_lib_name;
181
182 /**
183  * Our notification context.
184  */
185 static struct GNUNET_SERVER_NotificationContext *snc;
186
187 /**
188  * Head of the Client DLL
189  */
190 static struct NamestoreClient *client_head;
191
192 /**
193  * Tail of the Client DLL
194  */
195 static struct NamestoreClient *client_tail;
196
197 /**
198  * First active zone monitor.
199  */
200 static struct ZoneMonitor *monitor_head;
201
202 /**
203  * Last active zone monitor.
204  */
205 static struct ZoneMonitor *monitor_tail;
206
207 /**
208  * Notification context shared by all monitors.
209  */
210 static struct GNUNET_SERVER_NotificationContext *monitor_nc;
211
212
213
214 /**
215  * Task run during shutdown.
216  *
217  * @param cls unused
218  * @param tc unused
219  */
220 static void
221 cleanup_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
222 {
223   struct ZoneIteration *no;
224   struct NamestoreClient *nc;
225
226   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
227               "Stopping namestore service\n");
228   if (NULL != snc)
229   {
230     GNUNET_SERVER_notification_context_destroy (snc);
231     snc = NULL;
232   }
233   while (NULL != (nc = client_head))
234   {
235     while (NULL != (no = nc->op_head))
236     {
237       GNUNET_CONTAINER_DLL_remove (nc->op_head, nc->op_tail, no);
238       GNUNET_free (no);
239     }
240     GNUNET_CONTAINER_DLL_remove (client_head, client_tail, nc);
241     GNUNET_free (nc);
242   }
243   GNUNET_break (NULL == GNUNET_PLUGIN_unload (db_lib_name, GSN_database));
244   GNUNET_free (db_lib_name);
245   db_lib_name = NULL;
246   if (NULL != monitor_nc)
247   {
248     GNUNET_SERVER_notification_context_destroy (monitor_nc);
249     monitor_nc = NULL;
250   }
251 }
252
253
254 /**
255  * Called whenever a client is disconnected.
256  * Frees our resources associated with that client.
257  *
258  * @param cls closure
259  * @param client identification of the client
260  */
261 static void
262 client_disconnect_notification (void *cls, 
263                                 struct GNUNET_SERVER_Client *client)
264 {
265   struct ZoneIteration *no;
266   struct NamestoreClient *nc;
267   struct ZoneMonitor *zm;
268
269   if (NULL == client)
270     return;
271   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
272               "Client %p disconnected\n", 
273               client);
274   if (NULL == (nc = GNUNET_SERVER_client_get_user_context (client, struct NamestoreClient)))
275     return;
276   while (NULL != (no = nc->op_head))
277   {
278     GNUNET_CONTAINER_DLL_remove (nc->op_head, nc->op_tail, no);
279     GNUNET_free (no);
280   }
281   GNUNET_CONTAINER_DLL_remove (client_head, client_tail, nc);
282   GNUNET_free (nc);
283   for (zm = monitor_head; NULL != zm; zm = zm->next)
284   {
285     if (client == zm->nc->client)
286     {
287       GNUNET_CONTAINER_DLL_remove (monitor_head,
288                                    monitor_tail,
289                                    zm);
290       if (GNUNET_SCHEDULER_NO_TASK != zm->task)
291       {
292         GNUNET_SCHEDULER_cancel (zm->task);
293         zm->task = GNUNET_SCHEDULER_NO_TASK;
294       }
295       GNUNET_free (zm);
296       break;
297     }
298   }
299 }
300
301
302 /**
303  * Add a client to our list of active clients, if it is not yet
304  * in there.
305  *
306  * @param client client to add
307  * @return internal namestore client structure for this client
308  */
309 static struct NamestoreClient *
310 client_lookup (struct GNUNET_SERVER_Client *client)
311 {
312   struct NamestoreClient *nc;
313
314   nc = GNUNET_SERVER_client_get_user_context (client, struct NamestoreClient);
315   if (NULL != nc)
316     return nc;
317   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
318               "Client %p connected\n",
319               client);
320   nc = GNUNET_new (struct NamestoreClient);
321   nc->client = client;
322   GNUNET_SERVER_notification_context_add (snc, client);
323   GNUNET_CONTAINER_DLL_insert (client_head, client_tail, nc);
324   GNUNET_SERVER_client_set_user_context (client, nc);
325   return nc;
326 }
327
328
329 /**
330  * Context for name lookups passed from 'handle_lookup_name' to
331  * 'handle_lookup_name_it' as closure
332  */
333 struct LookupNameContext
334 {
335   /**
336    * The client to send the response to
337    */
338   struct NamestoreClient *nc;
339
340   /**
341    * Operation id for the name lookup
342    */
343   uint32_t request_id;
344
345 };
346
347
348 /**
349  * A #GNUNET_NAMESTORE_BlockCallback for name lookups in #handle_lookup_name
350  *
351  * @param cls a 'struct LookupNameContext *' with information about the request
352  * @param block the block
353  */
354 static void
355 handle_lookup_block_it (void *cls,
356                         const struct GNUNET_NAMESTORE_Block *block)
357 {
358   struct LookupNameContext *lnc = cls;
359   struct LookupBlockResponseMessage *r;
360   size_t esize;
361
362   esize = ntohl (block->purpose.size)
363     - sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) 
364     - sizeof (struct GNUNET_TIME_AbsoluteNBO);
365   r = GNUNET_malloc (sizeof (struct LookupBlockResponseMessage) + esize);
366   r->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_LOOKUP_BLOCK_RESPONSE);
367   r->gns_header.header.size = htons (sizeof (struct LookupBlockResponseMessage) + esize);
368   r->gns_header.r_id = htonl (lnc->request_id);
369   r->expire = block->expiration_time;
370   r->signature = block->signature;
371   r->derived_key = block->derived_key;  
372   memcpy (&r[1], &block[1], esize);
373   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
374               "Sending `%s' message\n", 
375               "NAMESTORE_LOOKUP_NAME_RESPONSE");
376   GNUNET_SERVER_notification_context_unicast (snc, 
377                                               lnc->nc->client, 
378                                               &r->gns_header.header, 
379                                               GNUNET_NO);
380   GNUNET_free (r);
381 }
382
383
384 /**
385  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_LOOKUP_BLOCK message
386  *
387  * @param cls unused
388  * @param client client sending the message
389  * @param message message of type 'struct LookupNameMessage'
390  */
391 static void
392 handle_lookup_block (void *cls,
393                     struct GNUNET_SERVER_Client *client,
394                     const struct GNUNET_MessageHeader *message)
395 {
396   const struct LookupBlockMessage *ln_msg;
397   struct LookupNameContext lnc;
398   struct NamestoreClient *nc;
399   struct LookupBlockResponseMessage zir_end;
400   int ret;
401
402   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
403               "Received `%s' message\n", 
404               "NAMESTORE_LOOKUP_NAME");
405   nc = client_lookup(client);
406   ln_msg = (const struct LookupBlockMessage *) message;
407   lnc.request_id = ntohl (ln_msg->gns_header.r_id);
408   lnc.nc = nc;
409   if (GNUNET_SYSERR ==
410       (ret = GSN_database->lookup_block (GSN_database->cls, 
411                                          &ln_msg->query,
412                                          &handle_lookup_block_it, &lnc)))
413   {
414     /* internal error (in database plugin); might be best to just hang up on
415        plugin rather than to signal that there are 'no' results, which 
416        might also be false... */
417     GNUNET_break (0); 
418     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
419     return;
420   }  
421   if (0 == ret)
422   {
423     /* no records match at all, generate empty response */
424     memset (&zir_end, 0, sizeof (zir_end));
425     zir_end.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_LOOKUP_BLOCK_RESPONSE);
426     zir_end.gns_header.header.size = htons (sizeof (struct LookupBlockResponseMessage));
427     zir_end.gns_header.r_id = ln_msg->gns_header.r_id;
428     GNUNET_SERVER_notification_context_unicast (snc, 
429                                                 client, 
430                                                 &zir_end.gns_header.header, 
431                                                 GNUNET_NO);
432
433   }
434   GNUNET_SERVER_receive_done (client, GNUNET_OK);
435 }
436
437
438 /**
439  * Handles a 'GNUNET_MESSAGE_TYPE_NAMESTORE_BLOCK_CACHE' message
440  *
441  * @param cls unused
442  * @param client GNUNET_SERVER_Client sending the message
443  * @param message message of type 'struct BlockCacheMessage'
444  */
445 static void
446 handle_block_cache (void *cls,
447                      struct GNUNET_SERVER_Client *client,
448                      const struct GNUNET_MessageHeader *message)
449 {
450   struct NamestoreClient *nc;
451   const struct BlockCacheMessage *rp_msg;  
452   struct BlockCacheResponseMessage rpr_msg;
453   struct GNUNET_NAMESTORE_Block *block;
454   size_t esize;
455   int res;
456
457   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
458               "Received `%s' message\n",
459               "NAMESTORE_BLOCK_CACHE");
460   nc = client_lookup (client);
461   if (ntohs (message->size) < sizeof (struct BlockCacheMessage))
462   {
463     GNUNET_break (0);
464     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
465     return;
466   }
467   rp_msg = (const struct BlockCacheMessage *) message;
468   esize = ntohs (rp_msg->gns_header.header.size) - sizeof (struct BlockCacheMessage);
469
470   block = GNUNET_malloc (sizeof (struct GNUNET_NAMESTORE_Block) + esize);
471   block->signature = rp_msg->signature;
472   block->derived_key = rp_msg->derived_key;
473   block->purpose.size = htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
474                                sizeof (struct GNUNET_TIME_AbsoluteNBO) +
475                                esize);
476   block->expiration_time = rp_msg->expire;
477   memcpy (&block[1], &rp_msg[1], esize);
478   res = GSN_database->cache_block (GSN_database->cls,
479                                    block);
480   GNUNET_free (block);
481
482   rpr_msg.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_BLOCK_CACHE_RESPONSE);
483   rpr_msg.gns_header.header.size = htons (sizeof (struct BlockCacheResponseMessage));
484   rpr_msg.gns_header.r_id = rp_msg->gns_header.r_id;
485   rpr_msg.op_result = htonl (res);
486   GNUNET_SERVER_notification_context_unicast (snc, 
487                                               nc->client, 
488                                               &rpr_msg.gns_header.header, 
489                                               GNUNET_NO);
490   GNUNET_SERVER_receive_done (client, GNUNET_OK);
491 }
492
493
494 /**
495  * Generate a 'struct LookupNameResponseMessage' and send it to the
496  * given client using the given notification context.
497  *
498  * @param nc notification context to use
499  * @param client client to unicast to
500  * @param request_id request ID to use
501  * @param zone_key zone key of the zone
502  * @param name name
503  * @param rd_count number of records
504  * @param rd array of records
505  */
506 static void
507 send_lookup_response (struct GNUNET_SERVER_NotificationContext *nc,                     
508                       struct GNUNET_SERVER_Client *client,
509                       uint32_t request_id,
510                       const struct GNUNET_CRYPTO_EccPrivateKey *zone_key,
511                       const char *name,
512                       unsigned int rd_count,
513                       const struct GNUNET_NAMESTORE_RecordData *rd)
514 {
515   struct RecordResultMessage *zir_msg;
516   size_t name_len;
517   size_t rd_ser_len;
518   size_t msg_size;
519   char *name_tmp;
520   char *rd_ser;
521
522   name_len = strlen (name) + 1;
523   rd_ser_len = GNUNET_NAMESTORE_records_get_size (rd_count, rd);  
524   msg_size = sizeof (struct RecordResultMessage) + name_len + rd_ser_len;
525
526   zir_msg = GNUNET_malloc (msg_size);
527   zir_msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT);
528   zir_msg->gns_header.header.size = htons (msg_size);
529   zir_msg->gns_header.r_id = htonl (request_id);
530   zir_msg->name_len = htons (name_len);
531   zir_msg->rd_count = htons (rd_count);
532   zir_msg->rd_len = htons (rd_ser_len);
533   zir_msg->private_key = *zone_key;
534   name_tmp = (char *) &zir_msg[1];
535   memcpy (name_tmp, name, name_len);
536   rd_ser = &name_tmp[name_len];
537   GNUNET_NAMESTORE_records_serialize (rd_count, rd, rd_ser_len, rd_ser);
538   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
539               "Sending `%s' message with size %u\n", 
540               "RECORD_RESULT",
541               msg_size);
542   GNUNET_SERVER_notification_context_unicast (nc,
543                                               client, 
544                                               &zir_msg->gns_header.header,
545                                               GNUNET_NO);
546   GNUNET_free (zir_msg);
547 }
548
549
550 /**
551  * Handles a 'GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE' message
552  *
553  * @param cls unused
554  * @param client client sending the message
555  * @param message message of type 'struct RecordCreateMessage'
556  */
557 static void
558 handle_record_store (void *cls,
559                       struct GNUNET_SERVER_Client *client,
560                       const struct GNUNET_MessageHeader *message)
561 {
562   struct NamestoreClient *nc;
563   const struct RecordStoreMessage *rp_msg;
564   struct RecordStoreResponseMessage rcr_msg;
565   size_t name_len;
566   size_t msg_size;
567   size_t msg_size_exp;
568   size_t rd_ser_len;
569   uint32_t rid;
570   const char *name_tmp;
571   char *conv_name;
572   const char *rd_ser;
573   unsigned int rd_count;
574   int res;
575   struct GNUNET_CRYPTO_EccPublicKey pubkey;
576
577   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
578               "Received `%s' message\n", 
579               "NAMESTORE_RECORD_STORE");
580   if (ntohs (message->size) < sizeof (struct RecordStoreMessage))
581   {
582     GNUNET_break (0);
583     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
584     return;
585   }
586   nc = client_lookup (client);
587   rp_msg = (const struct RecordStoreMessage *) message;
588   rid = ntohl (rp_msg->gns_header.r_id);
589   name_len = ntohs (rp_msg->name_len);
590   msg_size = ntohs (message->size);
591   rd_count = ntohs (rp_msg->rd_count);
592   rd_ser_len = ntohs (rp_msg->rd_len);
593   GNUNET_break (0 == ntohs (rp_msg->reserved));
594   msg_size_exp = sizeof (struct RecordStoreMessage) + name_len + rd_ser_len;
595   if (msg_size != msg_size_exp)
596   {
597     GNUNET_break (0);
598     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
599     return;
600   }
601   if ((0 == name_len) || (name_len > MAX_NAME_LEN))
602   {
603     GNUNET_break (0);
604     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
605     return;
606   }
607   name_tmp = (const char *) &rp_msg[1];
608   rd_ser = &name_tmp[name_len];
609   if ('\0' != name_tmp[name_len -1])
610   {
611     GNUNET_break (0);
612     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
613     return;
614   }
615   {
616     struct GNUNET_NAMESTORE_RecordData rd[rd_count];
617
618     if (GNUNET_OK !=
619         GNUNET_NAMESTORE_records_deserialize (rd_ser_len, rd_ser, rd_count, rd))
620     {
621       GNUNET_break (0);
622       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
623       return;
624     }
625
626     /* Extracting and converting private key */
627     GNUNET_CRYPTO_ecc_key_get_public (&rp_msg->private_key,
628                                       &pubkey);
629     conv_name = GNUNET_NAMESTORE_normalize_string (name_tmp);
630     if (NULL == conv_name)
631     {
632       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
633                   "Error converting name `%s'\n", name_tmp);
634       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
635       return;
636     }
637     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
638                 "Creating %u records for name `%s' in zone `%s'\n",
639                 (unsigned int) rd_count,
640                 conv_name,
641                 GNUNET_NAMESTORE_z2s (&pubkey));
642     res = GSN_database->store_records (GSN_database->cls,
643                                        &rp_msg->private_key,
644                                        conv_name,                                      
645                                        rd_count, rd);
646     if (GNUNET_OK == res)
647     {
648       struct ZoneMonitor *zm;
649       
650       for (zm = monitor_head; NULL != zm; zm = zm->next)    
651         if (0 == memcmp (&rp_msg->private_key,
652                          &zm->zone, 
653                          sizeof (struct GNUNET_CRYPTO_EccPrivateKey)))
654           send_lookup_response (monitor_nc,
655                                 zm->nc->client,
656                                 zm->request_id,
657                                 &rp_msg->private_key,
658                                 conv_name,
659                                 rd_count, rd);      
660     }    
661     GNUNET_free (conv_name);
662   }
663   
664   /* Send response */
665   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
666               "Sending `%s' message\n", 
667               "RECORD_STORE_RESPONSE");
668   rcr_msg.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE_RESPONSE);
669   rcr_msg.gns_header.header.size = htons (sizeof (struct RecordStoreResponseMessage));
670   rcr_msg.gns_header.r_id = htonl (rid);
671   rcr_msg.op_result = htonl (res);
672   GNUNET_SERVER_notification_context_unicast (snc, nc->client,
673                                               &rcr_msg.gns_header.header,
674                                               GNUNET_NO);
675   GNUNET_SERVER_receive_done (client, GNUNET_OK);
676 }
677
678
679 /**
680  * Context for record remove operations passed from 'handle_zone_to_name' to
681  * 'handle_zone_to_name_it' as closure
682  */
683 struct ZoneToNameCtx
684 {
685   /**
686    * Namestore client
687    */
688   struct NamestoreClient *nc;
689
690   /**
691    * Request id (to be used in the response to the client).
692    */
693   uint32_t rid;
694
695   /**
696    * Set to GNUNET_OK on success, GNUNET_SYSERR on error.  Note that
697    * not finding a name for the zone still counts as a 'success' here,
698    * as this field is about the success of executing the IPC protocol.
699    */
700   int success;
701 };
702
703
704 /**
705  * Zone to name iterator
706  *
707  * @param cls struct ZoneToNameCtx *
708  * @param zone_key the zone key
709  * @param name name
710  * @param rd_count number of records
711  * @param rd record data
712  */
713 static void
714 handle_zone_to_name_it (void *cls,
715                         const struct GNUNET_CRYPTO_EccPrivateKey *zone_key,
716                         const char *name,
717                         unsigned int rd_count,
718                         const struct GNUNET_NAMESTORE_RecordData *rd)
719 {
720   struct ZoneToNameCtx *ztn_ctx = cls;
721   struct ZoneToNameResponseMessage *ztnr_msg;
722   int16_t res;
723   size_t name_len;
724   size_t rd_ser_len;
725   size_t msg_size;
726   char *name_tmp;
727   char *rd_tmp;
728
729   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
730               "Found result for zone-to-name lookup: `%s'\n", 
731               name);
732   res = GNUNET_YES;
733   name_len = strlen (name) + 1;
734   rd_ser_len = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
735   msg_size = sizeof (struct ZoneToNameResponseMessage) + name_len + rd_ser_len;
736   if (msg_size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
737   {
738     GNUNET_break (0);
739     ztn_ctx->success = GNUNET_SYSERR;
740     return;
741   }
742   ztnr_msg = GNUNET_malloc (msg_size);
743   ztnr_msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME_RESPONSE);
744   ztnr_msg->gns_header.header.size = htons (msg_size);
745   ztnr_msg->gns_header.r_id = htonl (ztn_ctx->rid);
746   ztnr_msg->res = htons (res);
747   ztnr_msg->rd_len = htons (rd_ser_len);
748   ztnr_msg->rd_count = htons (rd_count);
749   ztnr_msg->name_len = htons (name_len);
750   ztnr_msg->zone = *zone_key;
751   name_tmp = (char *) &ztnr_msg[1];
752   if (NULL != name)
753     memcpy (name_tmp, name, name_len);
754   rd_tmp = &name_tmp[name_len];
755   GNUNET_NAMESTORE_records_serialize (rd_count, rd, rd_ser_len, rd_tmp);
756   ztn_ctx->success = GNUNET_OK;
757   GNUNET_SERVER_notification_context_unicast (snc, ztn_ctx->nc->client,
758                                               &ztnr_msg->gns_header.header,
759                                               GNUNET_NO);
760   GNUNET_free (ztnr_msg);
761 }
762
763
764 /**
765  * Handles a 'GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME' message
766  *
767  * @param cls unused
768  * @param client GNUNET_SERVER_Client sending the message
769  * @param message message of type 'struct ZoneToNameMessage'
770  */
771 static void
772 handle_zone_to_name (void *cls,
773                      struct GNUNET_SERVER_Client *client,
774                      const struct GNUNET_MessageHeader *message)
775 {
776   struct NamestoreClient *nc;
777   const struct ZoneToNameMessage *ztn_msg;
778   struct ZoneToNameCtx ztn_ctx;
779   struct ZoneToNameResponseMessage ztnr_msg;
780
781   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
782               "Received `%s' message\n",
783               "ZONE_TO_NAME");
784   ztn_msg = (const struct ZoneToNameMessage *) message;
785   nc = client_lookup (client);
786   ztn_ctx.rid = ntohl (ztn_msg->gns_header.r_id);
787   ztn_ctx.nc = nc;
788   ztn_ctx.success = GNUNET_NO;
789   if (GNUNET_SYSERR ==
790       GSN_database->zone_to_name (GSN_database->cls, 
791                                   &ztn_msg->zone,
792                                   &ztn_msg->value_zone,
793                                   &handle_zone_to_name_it, &ztn_ctx))
794   {
795     /* internal error, hang up instead of signalling something
796        that might be wrong */
797     GNUNET_break (0);
798     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
799     return;    
800   }
801   if (GNUNET_NO == ztn_ctx.success)
802   {
803     /* no result found, send empty response */
804     memset (&ztnr_msg, 0, sizeof (ztnr_msg));
805     ztnr_msg.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME_RESPONSE);
806     ztnr_msg.gns_header.header.size = htons (sizeof (ztnr_msg));
807     ztnr_msg.gns_header.r_id = ztn_msg->gns_header.r_id;
808     ztnr_msg.res = htons (GNUNET_NO);
809     GNUNET_SERVER_notification_context_unicast (snc,
810                                                 client,
811                                                 &ztnr_msg.gns_header.header,
812                                                 GNUNET_NO);
813   }
814   GNUNET_SERVER_receive_done (client, ztn_ctx.success);
815 }
816
817
818 /**
819  * Zone iteration processor result
820  */
821 enum ZoneIterationResult
822 {
823   /**
824    * Iteration start.
825    */
826   IT_START = 0,
827
828   /**
829    * Found records,
830    * Continue to iterate with next iteration_next call
831    */
832   IT_SUCCESS_MORE_AVAILABLE = 1,
833
834   /**
835    * Iteration complete
836    */
837   IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE = 2
838 };
839
840
841 /**
842  * Context for record remove operations passed from
843  * 'run_zone_iteration_round' to 'zone_iteraterate_proc' as closure
844  */
845 struct ZoneIterationProcResult
846 {
847   /**
848    * The zone iteration handle
849    */
850   struct ZoneIteration *zi;
851
852   /**
853    * Iteration result: iteration done?
854    * IT_SUCCESS_MORE_AVAILABLE:  if there may be more results overall but
855    * we got one for now and have sent it to the client
856    * IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE: if there are no further results,
857    * IT_ALL_RECORDS_FILTERED: if all results were filtered so far.
858    */
859   int res_iteration_finished;
860
861 };
862
863
864 /**
865  * Process results for zone iteration from database
866  *
867  * @param cls struct ZoneIterationProcResult *proc
868  * @param zone_key the zone key
869  * @param expire expiration time
870  * @param name name
871  * @param rd_count number of records for this name
872  * @param rd record data
873  * @param signature block signature
874  */
875 static void
876 zone_iteraterate_proc (void *cls,
877                        const struct GNUNET_CRYPTO_EccPrivateKey *zone_key,
878                        const char *name,
879                        unsigned int rd_count,
880                        const struct GNUNET_NAMESTORE_RecordData *rd)
881 {
882   struct ZoneIterationProcResult *proc = cls;
883
884   if ((NULL == zone_key) && (NULL == name))
885   {
886     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
887                 "Iteration done\n");
888     proc->res_iteration_finished = IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE;
889     return;
890   }
891   if ((NULL == zone_key) || (NULL == name)) 
892   {
893     /* what is this!? should never happen */
894     proc->res_iteration_finished = IT_START;
895     GNUNET_break (0);
896     return;    
897   }
898   proc->res_iteration_finished = IT_SUCCESS_MORE_AVAILABLE;
899   send_lookup_response (snc,
900                         proc->zi->client->client,
901                         proc->zi->request_id,
902                         zone_key,
903                         name,
904                         rd_count,
905                         rd);
906 }
907
908
909 /**
910  * Perform the next round of the zone iteration.
911  *
912  * @param zi zone iterator to process
913  */
914 static void
915 run_zone_iteration_round (struct ZoneIteration *zi)
916 {
917   struct ZoneIterationProcResult proc;
918   struct RecordResultMessage rrm;
919   int ret;
920
921   memset (&proc, 0, sizeof (proc));
922   proc.zi = zi;
923   proc.res_iteration_finished = IT_START;
924   while (IT_START == proc.res_iteration_finished)
925   {
926     if (GNUNET_SYSERR ==
927         (ret = GSN_database->iterate_records (GSN_database->cls, 
928                                               &zi->zone, 
929                                               zi->offset, 
930                                               &zone_iteraterate_proc, &proc)))
931     {
932       GNUNET_break (0);
933       break;
934     }
935     if (GNUNET_NO == ret)
936       proc.res_iteration_finished = IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE;
937     zi->offset++;
938   }
939   if (IT_SUCCESS_MORE_AVAILABLE == proc.res_iteration_finished)
940   {
941     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
942                 "More results available\n");
943     return; /* more results later */
944   }
945   /* send empty response to indicate end of list */
946   memset (&rrm, 0, sizeof (rrm));
947   rrm.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT);
948   rrm.gns_header.header.size = htons (sizeof (rrm));
949   rrm.gns_header.r_id = htonl (zi->request_id);
950   GNUNET_SERVER_notification_context_unicast (snc,
951                                               zi->client->client, 
952                                               &rrm.gns_header.header,
953                                               GNUNET_NO);
954   GNUNET_CONTAINER_DLL_remove (zi->client->op_head, 
955                                zi->client->op_tail,
956                                zi);
957   GNUNET_free (zi);
958 }
959
960
961 /**
962  * Handles a 'GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_START' message
963  *
964  * @param cls unused
965  * @param client GNUNET_SERVER_Client sending the message
966  * @param message message of type 'struct ZoneIterationStartMessage'
967  */
968 static void
969 handle_iteration_start (void *cls,
970                         struct GNUNET_SERVER_Client *client,
971                         const struct GNUNET_MessageHeader *message)
972 {
973   const struct ZoneIterationStartMessage *zis_msg;
974   struct NamestoreClient *nc;
975   struct ZoneIteration *zi;
976
977   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "ZONE_ITERATION_START");
978   if (NULL == (nc = client_lookup (client)))
979   {
980     GNUNET_break (0);
981     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
982     return;
983   }
984   zis_msg = (const struct ZoneIterationStartMessage *) message;
985   zi = GNUNET_new (struct ZoneIteration);
986   zi->request_id = ntohl (zis_msg->gns_header.r_id);
987   zi->offset = 0;
988   zi->client = nc;
989   zi->zone = zis_msg->zone;
990   GNUNET_CONTAINER_DLL_insert (nc->op_head, nc->op_tail, zi);
991   run_zone_iteration_round (zi);
992   GNUNET_SERVER_receive_done (client, GNUNET_OK);
993 }
994
995
996 /**
997  * Handles a 'GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_STOP' message
998  *
999  * @param cls unused
1000  * @param client GNUNET_SERVER_Client sending the message
1001  * @param message message of type 'struct ZoneIterationStopMessage'
1002  */
1003 static void
1004 handle_iteration_stop (void *cls,
1005                        struct GNUNET_SERVER_Client *client,
1006                        const struct GNUNET_MessageHeader *message)
1007 {
1008   struct NamestoreClient *nc;
1009   struct ZoneIteration *zi;
1010   const struct ZoneIterationStopMessage *zis_msg;
1011   uint32_t rid;
1012
1013   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1014               "Received `%s' message\n",
1015               "ZONE_ITERATION_STOP");
1016   if (NULL == (nc = client_lookup(client)))
1017   {
1018     GNUNET_break (0);
1019     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1020     return;
1021   }
1022   zis_msg = (const struct ZoneIterationStopMessage *) message;
1023   rid = ntohl (zis_msg->gns_header.r_id);
1024   for (zi = nc->op_head; NULL != zi; zi = zi->next)
1025     if (zi->request_id == rid)
1026       break;
1027   if (NULL == zi)
1028   {
1029     GNUNET_break (0);
1030     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1031     return;
1032   }
1033   GNUNET_CONTAINER_DLL_remove (nc->op_head, nc->op_tail, zi);
1034   GNUNET_free (zi);
1035   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1036 }
1037
1038
1039 /**
1040  * Handles a 'GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_NEXT' message
1041  *
1042  * @param cls unused
1043  * @param client GNUNET_SERVER_Client sending the message
1044  * @param message message of type 'struct ZoneIterationNextMessage'
1045  */
1046 static void
1047 handle_iteration_next (void *cls,
1048                        struct GNUNET_SERVER_Client *client,
1049                        const struct GNUNET_MessageHeader *message)
1050 {
1051   struct NamestoreClient *nc;
1052   struct ZoneIteration *zi;
1053   const struct ZoneIterationNextMessage *zis_msg;
1054   uint32_t rid;
1055
1056   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "ZONE_ITERATION_NEXT");
1057   if (NULL == (nc = client_lookup(client)))
1058   {
1059     GNUNET_break (0);
1060     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1061     return;
1062   }
1063   zis_msg = (const struct ZoneIterationNextMessage *) message;
1064   rid = ntohl (zis_msg->gns_header.r_id);
1065   for (zi = nc->op_head; NULL != zi; zi = zi->next)
1066     if (zi->request_id == rid)
1067       break;
1068   if (NULL == zi)
1069   {
1070     GNUNET_break (0);
1071     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1072     return;
1073   }
1074   run_zone_iteration_round (zi);
1075   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1076 }
1077
1078
1079 /**
1080  * Send 'sync' message to zone monitor, we're now in sync.
1081  *
1082  * @param zm monitor that is now in sync
1083  */ 
1084 static void
1085 monitor_sync (struct ZoneMonitor *zm)
1086 {
1087   struct GNUNET_MessageHeader sync;
1088
1089   sync.size = htons (sizeof (struct GNUNET_MessageHeader));
1090   sync.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_SYNC);
1091   GNUNET_SERVER_notification_context_unicast (monitor_nc,
1092                                               zm->nc->client,
1093                                               &sync,
1094                                               GNUNET_NO);
1095 }
1096
1097
1098 /**
1099  * Obtain the next datum during the zone monitor's zone intiial iteration.
1100  *
1101  * @param cls zone monitor that does its initial iteration
1102  * @param tc scheduler context
1103  */
1104 static void
1105 monitor_next (void *cls,
1106               const struct GNUNET_SCHEDULER_TaskContext *tc);
1107
1108
1109 /**
1110  * A 'GNUNET_NAMESTORE_RecordIterator' for monitors.
1111  *
1112  * @param cls a 'struct ZoneMonitor *' with information about the monitor
1113  * @param zone_key zone key of the zone
1114  * @param expire expiration time
1115  * @param name name
1116  * @param rd_count number of records
1117  * @param rd array of records
1118  * @param signature signature
1119  */
1120 static void
1121 monitor_iterate_cb (void *cls,
1122                     const struct GNUNET_CRYPTO_EccPrivateKey *zone_key,
1123                     const char *name,
1124                     unsigned int rd_count,
1125                     const struct GNUNET_NAMESTORE_RecordData *rd)
1126 {
1127   struct ZoneMonitor *zm = cls;
1128
1129   if (NULL == name)
1130   {
1131     /* finished with iteration */
1132     monitor_sync (zm);
1133     return;
1134   }
1135   send_lookup_response (monitor_nc,
1136                         zm->nc->client,
1137                         zm->request_id,
1138                         zone_key,
1139                         name,
1140                         rd_count,
1141                         rd);
1142   zm->task = GNUNET_SCHEDULER_add_now (&monitor_next, zm);
1143 }
1144
1145
1146 /**
1147  * Handles a 'GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_START' message
1148  *
1149  * @param cls unused
1150  * @param client GNUNET_SERVER_Client sending the message
1151  * @param message message of type 'struct ZoneMonitorStartMessage'
1152  */
1153 static void
1154 handle_monitor_start (void *cls,
1155                       struct GNUNET_SERVER_Client *client,
1156                       const struct GNUNET_MessageHeader *message)
1157 {
1158   const struct ZoneMonitorStartMessage *zis_msg;
1159   struct ZoneMonitor *zm;
1160   
1161   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1162               "Received `%s' message\n",
1163               "ZONE_MONITOR_START");
1164   zis_msg = (const struct ZoneMonitorStartMessage *) message;
1165   zm = GNUNET_new (struct ZoneMonitor);
1166   zm->request_id = ntohl (zis_msg->gns_header.r_id);
1167   zm->offset = 0;
1168   zm->nc = client_lookup (client);
1169   zm->zone = zis_msg->zone;
1170   GNUNET_CONTAINER_DLL_insert (monitor_head, monitor_tail, zm);
1171   GNUNET_SERVER_client_mark_monitor (client);
1172   GNUNET_SERVER_disable_receive_done_warning (client);
1173   GNUNET_SERVER_notification_context_add (monitor_nc,
1174                                           client);
1175   zm->task = GNUNET_SCHEDULER_add_now (&monitor_next, zm);  
1176 }
1177
1178
1179 /**
1180  * Obtain the next datum during the zone monitor's zone intiial iteration.
1181  *
1182  * @param cls zone monitor that does its initial iteration
1183  * @param tc scheduler context
1184  */
1185 static void
1186 monitor_next (void *cls,
1187               const struct GNUNET_SCHEDULER_TaskContext *tc)
1188 {
1189   struct ZoneMonitor *zm = cls;
1190   int ret;
1191   
1192   zm->task = GNUNET_SCHEDULER_NO_TASK;
1193   ret = GSN_database->iterate_records (GSN_database->cls,
1194                                        &zm->zone,
1195                                        zm->offset++,
1196                                        &monitor_iterate_cb, zm);
1197   if (GNUNET_SYSERR == ret)
1198   {
1199     GNUNET_SERVER_client_disconnect (zm->nc->client);
1200     return;
1201   }
1202   if (GNUNET_NO == ret)
1203   {
1204     /* empty zone */
1205     monitor_sync (zm);
1206     return;
1207   }
1208 }
1209
1210
1211 /**
1212  * Process namestore requests.
1213  *
1214  * @param cls closure
1215  * @param server the initialized server
1216  * @param cfg configuration to use
1217  */
1218 static void
1219 run (void *cls, struct GNUNET_SERVER_Handle *server,
1220      const struct GNUNET_CONFIGURATION_Handle *cfg)
1221 {
1222   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1223     {&handle_lookup_block, NULL,
1224      GNUNET_MESSAGE_TYPE_NAMESTORE_LOOKUP_BLOCK, sizeof (struct LookupBlockMessage)},
1225     {&handle_block_cache, NULL,
1226     GNUNET_MESSAGE_TYPE_NAMESTORE_BLOCK_CACHE, 0},
1227     {&handle_record_store, NULL,
1228      GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE, 0},
1229     {&handle_zone_to_name, NULL,
1230      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME, sizeof (struct ZoneToNameMessage) },
1231     {&handle_iteration_start, NULL,
1232      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_START, sizeof (struct ZoneIterationStartMessage) },
1233     {&handle_iteration_next, NULL,
1234      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_NEXT, sizeof (struct ZoneIterationNextMessage) },
1235     {&handle_iteration_stop, NULL,
1236      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_STOP, sizeof (struct ZoneIterationStopMessage) },
1237     {&handle_monitor_start, NULL,
1238      GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_START, sizeof (struct ZoneMonitorStartMessage) },
1239     {NULL, NULL, 0, 0}
1240   };
1241   char *database;
1242
1243   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting namestore service\n");
1244   GSN_cfg = cfg;
1245   monitor_nc = GNUNET_SERVER_notification_context_create (server, 1);
1246
1247   /* Loading database plugin */
1248   if (GNUNET_OK !=
1249       GNUNET_CONFIGURATION_get_value_string (cfg, "namestore", "database",
1250                                              &database))
1251     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No database backend configured\n");
1252
1253   GNUNET_asprintf (&db_lib_name, "libgnunet_plugin_namestore_%s", database);
1254   GSN_database = GNUNET_PLUGIN_load (db_lib_name, (void *) GSN_cfg);
1255   GNUNET_free (database);
1256   if (NULL == GSN_database)
1257   {
1258     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
1259                 "Could not load database backend `%s'\n",
1260                 db_lib_name);
1261     GNUNET_SCHEDULER_add_now (&cleanup_task, NULL);
1262     return;
1263   }
1264
1265   /* Configuring server handles */
1266   GNUNET_SERVER_add_handlers (server, handlers);
1267   snc = GNUNET_SERVER_notification_context_create (server, 16);
1268   GNUNET_SERVER_disconnect_notify (server,
1269                                    &client_disconnect_notification,
1270                                    NULL);
1271   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleanup_task,
1272                                 NULL);
1273 }
1274
1275
1276 /**
1277  * The main function for the template service.
1278  *
1279  * @param argc number of arguments from the command line
1280  * @param argv command line arguments
1281  * @return 0 ok, 1 on error
1282  */
1283 int
1284 main (int argc, char *const *argv)
1285 {
1286   return (GNUNET_OK ==
1287           GNUNET_SERVICE_run (argc, argv, "namestore",
1288                               GNUNET_SERVICE_OPTION_NONE, &run, NULL)) ? 0 : 1;
1289 }
1290
1291 /* end of gnunet-service-namestore.c */
1292