-if records are deleted, delete them from cache as well
[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_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_block to
331  * #handle_lookup_block_it as closure
332  */
333 struct LookupBlockContext
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_block
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 LookupBlockContext *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_BLOCK_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 LookupBlockContext 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_BLOCK");
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 in @a rd
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       struct GNUNET_NAMESTORE_Block *block;
650
651       if (0 == rd_count)
652         block = GNUNET_NAMESTORE_block_create (&rp_msg->private_key,
653                                                GNUNET_TIME_UNIT_ZERO_ABS,
654                                                conv_name,
655                                                rd, rd_count);
656       else
657         block = GNUNET_NAMESTORE_block_create (&rp_msg->private_key,
658                                                GNUNET_TIME_UNIT_FOREVER_ABS,
659                                                conv_name,
660                                                rd, rd_count);
661       if (GNUNET_OK !=
662           GSN_database->cache_block (GSN_database->cls,
663                                      block))
664       {
665         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
666                     _("Failed to cache encrypted block of my own zone!\n"));
667         res = GNUNET_SYSERR;
668       }
669       GNUNET_free (block);
670       
671       for (zm = monitor_head; NULL != zm; zm = zm->next)    
672         if (0 == memcmp (&rp_msg->private_key,
673                          &zm->zone, 
674                          sizeof (struct GNUNET_CRYPTO_EccPrivateKey)))
675           send_lookup_response (monitor_nc,
676                                 zm->nc->client,
677                                 zm->request_id,
678                                 &rp_msg->private_key,
679                                 conv_name,
680                                 rd_count, rd);      
681     }    
682     GNUNET_free (conv_name);
683   }
684   
685   /* Send response */
686   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
687               "Sending `%s' message\n", 
688               "RECORD_STORE_RESPONSE");
689   rcr_msg.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE_RESPONSE);
690   rcr_msg.gns_header.header.size = htons (sizeof (struct RecordStoreResponseMessage));
691   rcr_msg.gns_header.r_id = htonl (rid);
692   rcr_msg.op_result = htonl (res);
693   GNUNET_SERVER_notification_context_unicast (snc, nc->client,
694                                               &rcr_msg.gns_header.header,
695                                               GNUNET_NO);
696   GNUNET_SERVER_receive_done (client, GNUNET_OK);
697 }
698
699
700 /**
701  * Context for record remove operations passed from #handle_zone_to_name to
702  * #handle_zone_to_name_it as closure
703  */
704 struct ZoneToNameCtx
705 {
706   /**
707    * Namestore client
708    */
709   struct NamestoreClient *nc;
710
711   /**
712    * Request id (to be used in the response to the client).
713    */
714   uint32_t rid;
715
716   /**
717    * Set to #GNUNET_OK on success, #GNUNET_SYSERR on error.  Note that
718    * not finding a name for the zone still counts as a 'success' here,
719    * as this field is about the success of executing the IPC protocol.
720    */
721   int success;
722 };
723
724
725 /**
726  * Zone to name iterator
727  *
728  * @param cls struct ZoneToNameCtx *
729  * @param zone_key the zone key
730  * @param name name
731  * @param rd_count number of records in @a rd
732  * @param rd record data
733  */
734 static void
735 handle_zone_to_name_it (void *cls,
736                         const struct GNUNET_CRYPTO_EccPrivateKey *zone_key,
737                         const char *name,
738                         unsigned int rd_count,
739                         const struct GNUNET_NAMESTORE_RecordData *rd)
740 {
741   struct ZoneToNameCtx *ztn_ctx = cls;
742   struct ZoneToNameResponseMessage *ztnr_msg;
743   int16_t res;
744   size_t name_len;
745   size_t rd_ser_len;
746   size_t msg_size;
747   char *name_tmp;
748   char *rd_tmp;
749
750   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
751               "Found result for zone-to-name lookup: `%s'\n", 
752               name);
753   res = GNUNET_YES;
754   name_len = strlen (name) + 1;
755   rd_ser_len = GNUNET_NAMESTORE_records_get_size (rd_count, rd);
756   msg_size = sizeof (struct ZoneToNameResponseMessage) + name_len + rd_ser_len;
757   if (msg_size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
758   {
759     GNUNET_break (0);
760     ztn_ctx->success = GNUNET_SYSERR;
761     return;
762   }
763   ztnr_msg = GNUNET_malloc (msg_size);
764   ztnr_msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME_RESPONSE);
765   ztnr_msg->gns_header.header.size = htons (msg_size);
766   ztnr_msg->gns_header.r_id = htonl (ztn_ctx->rid);
767   ztnr_msg->res = htons (res);
768   ztnr_msg->rd_len = htons (rd_ser_len);
769   ztnr_msg->rd_count = htons (rd_count);
770   ztnr_msg->name_len = htons (name_len);
771   ztnr_msg->zone = *zone_key;
772   name_tmp = (char *) &ztnr_msg[1];
773   if (NULL != name)
774     memcpy (name_tmp, name, name_len);
775   rd_tmp = &name_tmp[name_len];
776   GNUNET_NAMESTORE_records_serialize (rd_count, rd, rd_ser_len, rd_tmp);
777   ztn_ctx->success = GNUNET_OK;
778   GNUNET_SERVER_notification_context_unicast (snc, ztn_ctx->nc->client,
779                                               &ztnr_msg->gns_header.header,
780                                               GNUNET_NO);
781   GNUNET_free (ztnr_msg);
782 }
783
784
785 /**
786  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME message
787  *
788  * @param cls unused
789  * @param client client sending the message
790  * @param message message of type 'struct ZoneToNameMessage'
791  */
792 static void
793 handle_zone_to_name (void *cls,
794                      struct GNUNET_SERVER_Client *client,
795                      const struct GNUNET_MessageHeader *message)
796 {
797   struct NamestoreClient *nc;
798   const struct ZoneToNameMessage *ztn_msg;
799   struct ZoneToNameCtx ztn_ctx;
800   struct ZoneToNameResponseMessage ztnr_msg;
801
802   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
803               "Received `%s' message\n",
804               "ZONE_TO_NAME");
805   ztn_msg = (const struct ZoneToNameMessage *) message;
806   nc = client_lookup (client);
807   ztn_ctx.rid = ntohl (ztn_msg->gns_header.r_id);
808   ztn_ctx.nc = nc;
809   ztn_ctx.success = GNUNET_NO;
810   if (GNUNET_SYSERR ==
811       GSN_database->zone_to_name (GSN_database->cls, 
812                                   &ztn_msg->zone,
813                                   &ztn_msg->value_zone,
814                                   &handle_zone_to_name_it, &ztn_ctx))
815   {
816     /* internal error, hang up instead of signalling something
817        that might be wrong */
818     GNUNET_break (0);
819     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
820     return;    
821   }
822   if (GNUNET_NO == ztn_ctx.success)
823   {
824     /* no result found, send empty response */
825     memset (&ztnr_msg, 0, sizeof (ztnr_msg));
826     ztnr_msg.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME_RESPONSE);
827     ztnr_msg.gns_header.header.size = htons (sizeof (ztnr_msg));
828     ztnr_msg.gns_header.r_id = ztn_msg->gns_header.r_id;
829     ztnr_msg.res = htons (GNUNET_NO);
830     GNUNET_SERVER_notification_context_unicast (snc,
831                                                 client,
832                                                 &ztnr_msg.gns_header.header,
833                                                 GNUNET_NO);
834   }
835   GNUNET_SERVER_receive_done (client, ztn_ctx.success);
836 }
837
838
839 /**
840  * Zone iteration processor result
841  */
842 enum ZoneIterationResult
843 {
844   /**
845    * Iteration start.
846    */
847   IT_START = 0,
848
849   /**
850    * Found records,
851    * Continue to iterate with next iteration_next call
852    */
853   IT_SUCCESS_MORE_AVAILABLE = 1,
854
855   /**
856    * Iteration complete
857    */
858   IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE = 2
859 };
860
861
862 /**
863  * Context for record remove operations passed from
864  * 'run_zone_iteration_round' to 'zone_iteraterate_proc' as closure
865  */
866 struct ZoneIterationProcResult
867 {
868   /**
869    * The zone iteration handle
870    */
871   struct ZoneIteration *zi;
872
873   /**
874    * Iteration result: iteration done?
875    * #IT_SUCCESS_MORE_AVAILABLE:  if there may be more results overall but
876    * we got one for now and have sent it to the client
877    * #IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE: if there are no further results,
878    * #IT_START: if we are still trying to find a result.
879    */
880   int res_iteration_finished;
881
882 };
883
884
885 /**
886  * Process results for zone iteration from database
887  *
888  * @param cls struct ZoneIterationProcResult *proc
889  * @param zone_key the zone key
890  * @param name name
891  * @param rd_count number of records for this name
892  * @param rd record data
893  */
894 static void
895 zone_iteraterate_proc (void *cls,
896                        const struct GNUNET_CRYPTO_EccPrivateKey *zone_key,
897                        const char *name,
898                        unsigned int rd_count,
899                        const struct GNUNET_NAMESTORE_RecordData *rd)
900 {
901   struct ZoneIterationProcResult *proc = cls;
902
903   if ((NULL == zone_key) && (NULL == name))
904   {
905     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
906                 "Iteration done\n");
907     proc->res_iteration_finished = IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE;
908     return;
909   }
910   if ((NULL == zone_key) || (NULL == name)) 
911   {
912     /* what is this!? should never happen */
913     proc->res_iteration_finished = IT_START;
914     GNUNET_break (0);
915     return;    
916   }
917   proc->res_iteration_finished = IT_SUCCESS_MORE_AVAILABLE;
918   send_lookup_response (snc,
919                         proc->zi->client->client,
920                         proc->zi->request_id,
921                         zone_key,
922                         name,
923                         rd_count,
924                         rd);
925 }
926
927
928 /**
929  * Perform the next round of the zone iteration.
930  *
931  * @param zi zone iterator to process
932  */
933 static void
934 run_zone_iteration_round (struct ZoneIteration *zi)
935 {
936   struct ZoneIterationProcResult proc;
937   struct RecordResultMessage rrm;
938   int ret;
939
940   memset (&proc, 0, sizeof (proc));
941   proc.zi = zi;
942   proc.res_iteration_finished = IT_START;
943   while (IT_START == proc.res_iteration_finished)
944   {
945     if (GNUNET_SYSERR ==
946         (ret = GSN_database->iterate_records (GSN_database->cls, 
947                                               &zi->zone, 
948                                               zi->offset, 
949                                               &zone_iteraterate_proc, &proc)))
950     {
951       GNUNET_break (0);
952       break;
953     }
954     if (GNUNET_NO == ret)
955       proc.res_iteration_finished = IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE;
956     zi->offset++;
957   }
958   if (IT_SUCCESS_MORE_AVAILABLE == proc.res_iteration_finished)
959   {
960     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
961                 "More results available\n");
962     return; /* more results later */
963   }
964   /* send empty response to indicate end of list */
965   memset (&rrm, 0, sizeof (rrm));
966   rrm.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT);
967   rrm.gns_header.header.size = htons (sizeof (rrm));
968   rrm.gns_header.r_id = htonl (zi->request_id);
969   GNUNET_SERVER_notification_context_unicast (snc,
970                                               zi->client->client, 
971                                               &rrm.gns_header.header,
972                                               GNUNET_NO);
973   GNUNET_CONTAINER_DLL_remove (zi->client->op_head, 
974                                zi->client->op_tail,
975                                zi);
976   GNUNET_free (zi);
977 }
978
979
980 /**
981  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_START message
982  *
983  * @param cls unused
984  * @param client GNUNET_SERVER_Client sending the message
985  * @param message message of type 'struct ZoneIterationStartMessage'
986  */
987 static void
988 handle_iteration_start (void *cls,
989                         struct GNUNET_SERVER_Client *client,
990                         const struct GNUNET_MessageHeader *message)
991 {
992   const struct ZoneIterationStartMessage *zis_msg;
993   struct NamestoreClient *nc;
994   struct ZoneIteration *zi;
995
996   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "ZONE_ITERATION_START");
997   if (NULL == (nc = client_lookup (client)))
998   {
999     GNUNET_break (0);
1000     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1001     return;
1002   }
1003   zis_msg = (const struct ZoneIterationStartMessage *) message;
1004   zi = GNUNET_new (struct ZoneIteration);
1005   zi->request_id = ntohl (zis_msg->gns_header.r_id);
1006   zi->offset = 0;
1007   zi->client = nc;
1008   zi->zone = zis_msg->zone;
1009   GNUNET_CONTAINER_DLL_insert (nc->op_head, nc->op_tail, zi);
1010   run_zone_iteration_round (zi);
1011   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1012 }
1013
1014
1015 /**
1016  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_STOP message
1017  *
1018  * @param cls unused
1019  * @param client GNUNET_SERVER_Client sending the message
1020  * @param message message of type 'struct ZoneIterationStopMessage'
1021  */
1022 static void
1023 handle_iteration_stop (void *cls,
1024                        struct GNUNET_SERVER_Client *client,
1025                        const struct GNUNET_MessageHeader *message)
1026 {
1027   struct NamestoreClient *nc;
1028   struct ZoneIteration *zi;
1029   const struct ZoneIterationStopMessage *zis_msg;
1030   uint32_t rid;
1031
1032   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1033               "Received `%s' message\n",
1034               "ZONE_ITERATION_STOP");
1035   if (NULL == (nc = client_lookup(client)))
1036   {
1037     GNUNET_break (0);
1038     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1039     return;
1040   }
1041   zis_msg = (const struct ZoneIterationStopMessage *) message;
1042   rid = ntohl (zis_msg->gns_header.r_id);
1043   for (zi = nc->op_head; NULL != zi; zi = zi->next)
1044     if (zi->request_id == rid)
1045       break;
1046   if (NULL == zi)
1047   {
1048     GNUNET_break (0);
1049     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1050     return;
1051   }
1052   GNUNET_CONTAINER_DLL_remove (nc->op_head, nc->op_tail, zi);
1053   GNUNET_free (zi);
1054   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1055 }
1056
1057
1058 /**
1059  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_NEXT message
1060  *
1061  * @param cls unused
1062  * @param client GNUNET_SERVER_Client sending the message
1063  * @param message message of type 'struct ZoneIterationNextMessage'
1064  */
1065 static void
1066 handle_iteration_next (void *cls,
1067                        struct GNUNET_SERVER_Client *client,
1068                        const struct GNUNET_MessageHeader *message)
1069 {
1070   struct NamestoreClient *nc;
1071   struct ZoneIteration *zi;
1072   const struct ZoneIterationNextMessage *zis_msg;
1073   uint32_t rid;
1074
1075   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "ZONE_ITERATION_NEXT");
1076   if (NULL == (nc = client_lookup(client)))
1077   {
1078     GNUNET_break (0);
1079     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1080     return;
1081   }
1082   zis_msg = (const struct ZoneIterationNextMessage *) message;
1083   rid = ntohl (zis_msg->gns_header.r_id);
1084   for (zi = nc->op_head; NULL != zi; zi = zi->next)
1085     if (zi->request_id == rid)
1086       break;
1087   if (NULL == zi)
1088   {
1089     GNUNET_break (0);
1090     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1091     return;
1092   }
1093   run_zone_iteration_round (zi);
1094   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1095 }
1096
1097
1098 /**
1099  * Send 'sync' message to zone monitor, we're now in sync.
1100  *
1101  * @param zm monitor that is now in sync
1102  */ 
1103 static void
1104 monitor_sync (struct ZoneMonitor *zm)
1105 {
1106   struct GNUNET_MessageHeader sync;
1107
1108   sync.size = htons (sizeof (struct GNUNET_MessageHeader));
1109   sync.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_SYNC);
1110   GNUNET_SERVER_notification_context_unicast (monitor_nc,
1111                                               zm->nc->client,
1112                                               &sync,
1113                                               GNUNET_NO);
1114 }
1115
1116
1117 /**
1118  * Obtain the next datum during the zone monitor's zone intiial iteration.
1119  *
1120  * @param cls zone monitor that does its initial iteration
1121  * @param tc scheduler context
1122  */
1123 static void
1124 monitor_next (void *cls,
1125               const struct GNUNET_SCHEDULER_TaskContext *tc);
1126
1127
1128 /**
1129  * A #GNUNET_NAMESTORE_RecordIterator for monitors.
1130  *
1131  * @param cls a 'struct ZoneMonitor *' with information about the monitor
1132  * @param zone_key zone key of the zone
1133  * @param name name
1134  * @param rd_count number of records in @a rd
1135  * @param rd array of records
1136  */
1137 static void
1138 monitor_iterate_cb (void *cls,
1139                     const struct GNUNET_CRYPTO_EccPrivateKey *zone_key,
1140                     const char *name,
1141                     unsigned int rd_count,
1142                     const struct GNUNET_NAMESTORE_RecordData *rd)
1143 {
1144   struct ZoneMonitor *zm = cls;
1145
1146   if (NULL == name)
1147   {
1148     /* finished with iteration */
1149     monitor_sync (zm);
1150     return;
1151   }
1152   send_lookup_response (monitor_nc,
1153                         zm->nc->client,
1154                         zm->request_id,
1155                         zone_key,
1156                         name,
1157                         rd_count,
1158                         rd);
1159   zm->task = GNUNET_SCHEDULER_add_now (&monitor_next, zm);
1160 }
1161
1162
1163 /**
1164  * Handles a 'GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_START' message
1165  *
1166  * @param cls unused
1167  * @param client GNUNET_SERVER_Client sending the message
1168  * @param message message of type 'struct ZoneMonitorStartMessage'
1169  */
1170 static void
1171 handle_monitor_start (void *cls,
1172                       struct GNUNET_SERVER_Client *client,
1173                       const struct GNUNET_MessageHeader *message)
1174 {
1175   const struct ZoneMonitorStartMessage *zis_msg;
1176   struct ZoneMonitor *zm;
1177   
1178   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1179               "Received `%s' message\n",
1180               "ZONE_MONITOR_START");
1181   zis_msg = (const struct ZoneMonitorStartMessage *) message;
1182   zm = GNUNET_new (struct ZoneMonitor);
1183   zm->request_id = ntohl (zis_msg->gns_header.r_id);
1184   zm->offset = 0;
1185   zm->nc = client_lookup (client);
1186   zm->zone = zis_msg->zone;
1187   GNUNET_CONTAINER_DLL_insert (monitor_head, monitor_tail, zm);
1188   GNUNET_SERVER_client_mark_monitor (client);
1189   GNUNET_SERVER_disable_receive_done_warning (client);
1190   GNUNET_SERVER_notification_context_add (monitor_nc,
1191                                           client);
1192   zm->task = GNUNET_SCHEDULER_add_now (&monitor_next, zm);  
1193 }
1194
1195
1196 /**
1197  * Obtain the next datum during the zone monitor's zone intiial iteration.
1198  *
1199  * @param cls zone monitor that does its initial iteration
1200  * @param tc scheduler context
1201  */
1202 static void
1203 monitor_next (void *cls,
1204               const struct GNUNET_SCHEDULER_TaskContext *tc)
1205 {
1206   struct ZoneMonitor *zm = cls;
1207   int ret;
1208   
1209   zm->task = GNUNET_SCHEDULER_NO_TASK;
1210   ret = GSN_database->iterate_records (GSN_database->cls,
1211                                        &zm->zone,
1212                                        zm->offset++,
1213                                        &monitor_iterate_cb, zm);
1214   if (GNUNET_SYSERR == ret)
1215   {
1216     GNUNET_SERVER_client_disconnect (zm->nc->client);
1217     return;
1218   }
1219   if (GNUNET_NO == ret)
1220   {
1221     /* empty zone */
1222     monitor_sync (zm);
1223     return;
1224   }
1225 }
1226
1227
1228 /**
1229  * Process namestore requests.
1230  *
1231  * @param cls closure
1232  * @param server the initialized server
1233  * @param cfg configuration to use
1234  */
1235 static void
1236 run (void *cls, struct GNUNET_SERVER_Handle *server,
1237      const struct GNUNET_CONFIGURATION_Handle *cfg)
1238 {
1239   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1240     {&handle_lookup_block, NULL,
1241      GNUNET_MESSAGE_TYPE_NAMESTORE_LOOKUP_BLOCK, sizeof (struct LookupBlockMessage)},
1242     {&handle_block_cache, NULL,
1243     GNUNET_MESSAGE_TYPE_NAMESTORE_BLOCK_CACHE, 0},
1244     {&handle_record_store, NULL,
1245      GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE, 0},
1246     {&handle_zone_to_name, NULL,
1247      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME, sizeof (struct ZoneToNameMessage) },
1248     {&handle_iteration_start, NULL,
1249      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_START, sizeof (struct ZoneIterationStartMessage) },
1250     {&handle_iteration_next, NULL,
1251      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_NEXT, sizeof (struct ZoneIterationNextMessage) },
1252     {&handle_iteration_stop, NULL,
1253      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_STOP, sizeof (struct ZoneIterationStopMessage) },
1254     {&handle_monitor_start, NULL,
1255      GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_START, sizeof (struct ZoneMonitorStartMessage) },
1256     {NULL, NULL, 0, 0}
1257   };
1258   char *database;
1259
1260   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting namestore service\n");
1261   GSN_cfg = cfg;
1262   monitor_nc = GNUNET_SERVER_notification_context_create (server, 1);
1263
1264   /* Loading database plugin */
1265   if (GNUNET_OK !=
1266       GNUNET_CONFIGURATION_get_value_string (cfg, "namestore", "database",
1267                                              &database))
1268     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No database backend configured\n");
1269
1270   GNUNET_asprintf (&db_lib_name, "libgnunet_plugin_namestore_%s", database);
1271   GSN_database = GNUNET_PLUGIN_load (db_lib_name, (void *) GSN_cfg);
1272   GNUNET_free (database);
1273   if (NULL == GSN_database)
1274   {
1275     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
1276                 "Could not load database backend `%s'\n",
1277                 db_lib_name);
1278     GNUNET_SCHEDULER_add_now (&cleanup_task, NULL);
1279     return;
1280   }
1281
1282   /* Configuring server handles */
1283   GNUNET_SERVER_add_handlers (server, handlers);
1284   snc = GNUNET_SERVER_notification_context_create (server, 16);
1285   GNUNET_SERVER_disconnect_notify (server,
1286                                    &client_disconnect_notification,
1287                                    NULL);
1288   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleanup_task,
1289                                 NULL);
1290 }
1291
1292
1293 /**
1294  * The main function for the template service.
1295  *
1296  * @param argc number of arguments from the command line
1297  * @param argv command line arguments
1298  * @return 0 ok, 1 on error
1299  */
1300 int
1301 main (int argc, char *const *argv)
1302 {
1303   return (GNUNET_OK ==
1304           GNUNET_SERVICE_run (argc, argv, "namestore",
1305                               GNUNET_SERVICE_OPTION_NONE, &run, NULL)) ? 0 : 1;
1306 }
1307
1308 /* end of gnunet-service-namestore.c */
1309