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