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