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