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