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