fix for size
[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_gns_service.h"
31 #include "gnunet_namecache_service.h"
32 #include "gnunet_namestore_service.h"
33 #include "gnunet_namestore_plugin.h"
34 #include "gnunet_signatures.h"
35 #include "namestore.h"
36
37 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
38
39
40 /**
41  * A namestore client
42  */
43 struct NamestoreClient;
44
45
46 /**
47  * A namestore iteration operation.
48  */
49 struct ZoneIteration
50 {
51   /**
52    * Next element in the DLL
53    */
54   struct ZoneIteration *next;
55
56   /**
57    * Previous element in the DLL
58    */
59   struct ZoneIteration *prev;
60
61   /**
62    * Namestore client which intiated this zone iteration
63    */
64   struct NamestoreClient *client;
65
66   /**
67    * The nick to add to the records
68    */
69   struct GNUNET_GNSRECORD_Data *nick;
70
71   /**
72    * Key of the zone we are iterating over.
73    */
74   struct GNUNET_CRYPTO_EcdsaPrivateKey zone;
75
76   /**
77    * The operation id fot the zone iteration in the response for the client
78    */
79   uint32_t request_id;
80
81   /**
82    * Offset of the zone iteration used to address next result of the zone
83    * iteration in the store
84    *
85    * Initialy set to 0 in handle_iteration_start
86    * Incremented with by every call to handle_iteration_next
87    */
88   uint32_t offset;
89
90 };
91
92
93 /**
94  * A namestore client
95  */
96 struct NamestoreClient
97 {
98   /**
99    * Next element in the DLL
100    */
101   struct NamestoreClient *next;
102
103   /**
104    * Previous element in the DLL
105    */
106   struct NamestoreClient *prev;
107
108   /**
109    * The client
110    */
111   struct GNUNET_SERVER_Client *client;
112
113   /**
114    * Head of the DLL of
115    * Zone iteration operations in progress initiated by this client
116    */
117   struct ZoneIteration *op_head;
118
119   /**
120    * Tail of the DLL of
121    * Zone iteration operations in progress initiated by this client
122    */
123   struct ZoneIteration *op_tail;
124 };
125
126
127 /**
128  * A namestore monitor.
129  */
130 struct ZoneMonitor
131 {
132   /**
133    * Next element in the DLL
134    */
135   struct ZoneMonitor *next;
136
137   /**
138    * Previous element in the DLL
139    */
140   struct ZoneMonitor *prev;
141
142   /**
143    * Namestore client which intiated this zone monitor
144    */
145   struct NamestoreClient *nc;
146
147   /**
148    * Private key of the zone.
149    */
150   struct GNUNET_CRYPTO_EcdsaPrivateKey zone;
151
152   /**
153    * Task active during initial iteration.
154    */
155   GNUNET_SCHEDULER_TaskIdentifier task;
156
157   /**
158    * Offset of the zone iteration used to address next result of the zone
159    * iteration in the store
160    *
161    * Initialy set to 0.
162    * Incremented with by every call to #handle_iteration_next
163    */
164   uint32_t offset;
165
166 };
167
168
169 /**
170  * Pending operation on the namecache.
171  */
172 struct CacheOperation
173 {
174
175   /**
176    * Kept in a DLL.
177    */
178   struct CacheOperation *prev;
179
180   /**
181    * Kept in a DLL.
182    */
183   struct CacheOperation *next;
184
185   /**
186    * Handle to namecache queue.
187    */
188   struct GNUNET_NAMECACHE_QueueEntry *qe;
189
190   /**
191    * Client to notify about the result.
192    */
193   struct GNUNET_SERVER_Client *client;
194
195   /**
196    * Client's request ID.
197    */
198   uint32_t rid;
199 };
200
201
202 /**
203  * Public key of all zeros.
204  */
205 static const struct GNUNET_CRYPTO_EcdsaPrivateKey zero;
206
207 /**
208  * Configuration handle.
209  */
210 static const struct GNUNET_CONFIGURATION_Handle *GSN_cfg;
211
212 /**
213  * Namecache handle.
214  */
215 static struct GNUNET_NAMECACHE_Handle *namecache;
216
217 /**
218  * Database handle
219  */
220 static struct GNUNET_NAMESTORE_PluginFunctions *GSN_database;
221
222 /**
223  * Name of the database plugin
224  */
225 static char *db_lib_name;
226
227 /**
228  * Our notification context.
229  */
230 static struct GNUNET_SERVER_NotificationContext *snc;
231
232 /**
233  * Head of the Client DLL
234  */
235 static struct NamestoreClient *client_head;
236
237 /**
238  * Tail of the Client DLL
239  */
240 static struct NamestoreClient *client_tail;
241
242 /**
243  * Head of cop DLL.
244  */
245 static struct CacheOperation *cop_head;
246
247 /**
248  * Tail of cop DLL.
249  */
250 static struct CacheOperation *cop_tail;
251
252 /**
253  * First active zone monitor.
254  */
255 static struct ZoneMonitor *monitor_head;
256
257 /**
258  * Last active zone monitor.
259  */
260 static struct ZoneMonitor *monitor_tail;
261
262 /**
263  * Notification context shared by all monitors.
264  */
265 static struct GNUNET_SERVER_NotificationContext *monitor_nc;
266
267
268
269 /**
270  * Task run during shutdown.
271  *
272  * @param cls unused
273  * @param tc unused
274  */
275 static void
276 cleanup_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
277 {
278   struct ZoneIteration *no;
279   struct NamestoreClient *nc;
280   struct CacheOperation *cop;
281
282   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
283               "Stopping namestore service\n");
284   if (NULL != snc)
285   {
286     GNUNET_SERVER_notification_context_destroy (snc);
287     snc = NULL;
288   }
289   while (NULL != (cop = cop_head))
290   {
291     GNUNET_NAMECACHE_cancel (cop->qe);
292     GNUNET_CONTAINER_DLL_remove (cop_head,
293                                  cop_tail,
294                                  cop);
295     GNUNET_free (cop);
296   }
297   GNUNET_NAMECACHE_disconnect (namecache);
298   namecache = NULL;
299   while (NULL != (nc = client_head))
300   {
301     while (NULL != (no = nc->op_head))
302     {
303       GNUNET_CONTAINER_DLL_remove (nc->op_head, nc->op_tail, no);
304       GNUNET_free (no);
305     }
306     GNUNET_CONTAINER_DLL_remove (client_head, client_tail, nc);
307     GNUNET_SERVER_client_set_user_context (nc->client, (void *)NULL);
308     GNUNET_free (nc);
309   }
310   GNUNET_break (NULL == GNUNET_PLUGIN_unload (db_lib_name, GSN_database));
311   GNUNET_free (db_lib_name);
312   db_lib_name = NULL;
313   if (NULL != monitor_nc)
314   {
315     GNUNET_SERVER_notification_context_destroy (monitor_nc);
316     monitor_nc = NULL;
317   }
318 }
319
320
321 /**
322  * Called whenever a client is disconnected.
323  * Frees our resources associated with that client.
324  *
325  * @param cls closure
326  * @param client identification of the client
327  */
328 static void
329 client_disconnect_notification (void *cls,
330                                 struct GNUNET_SERVER_Client *client)
331 {
332   struct ZoneIteration *no;
333   struct NamestoreClient *nc;
334   struct ZoneMonitor *zm;
335   struct CacheOperation *cop;
336
337   if (NULL == client)
338     return;
339   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
340               "Client %p disconnected\n",
341               client);
342   if (NULL == (nc = GNUNET_SERVER_client_get_user_context (client, struct NamestoreClient)))
343     return;
344   while (NULL != (no = nc->op_head))
345   {
346     GNUNET_CONTAINER_DLL_remove (nc->op_head, nc->op_tail, no);
347     GNUNET_free (no);
348   }
349   GNUNET_CONTAINER_DLL_remove (client_head, client_tail, nc);
350   GNUNET_free (nc);
351   for (zm = monitor_head; NULL != zm; zm = zm->next)
352   {
353     if (client == zm->nc->client)
354     {
355       GNUNET_CONTAINER_DLL_remove (monitor_head,
356                                    monitor_tail,
357                                    zm);
358       if (GNUNET_SCHEDULER_NO_TASK != zm->task)
359       {
360         GNUNET_SCHEDULER_cancel (zm->task);
361         zm->task = GNUNET_SCHEDULER_NO_TASK;
362       }
363       GNUNET_free (zm);
364       break;
365     }
366   }
367   for (cop = cop_head; NULL != cop; cop = cop->next)
368     if (client == cop->client)
369       cop->client = NULL;
370 }
371
372
373 /**
374  * Add a client to our list of active clients, if it is not yet
375  * in there.
376  *
377  * @param client client to add
378  * @return internal namestore client structure for this client
379  */
380 static struct NamestoreClient *
381 client_lookup (struct GNUNET_SERVER_Client *client)
382 {
383   struct NamestoreClient *nc;
384
385   nc = GNUNET_SERVER_client_get_user_context (client, struct NamestoreClient);
386   if (NULL != nc)
387     return nc;
388   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
389               "Client %p connected\n",
390               client);
391   nc = GNUNET_new (struct NamestoreClient);
392   nc->client = client;
393   GNUNET_SERVER_notification_context_add (snc, client);
394   GNUNET_CONTAINER_DLL_insert (client_head, client_tail, nc);
395   GNUNET_SERVER_client_set_user_context (client, nc);
396   return nc;
397 }
398
399
400 static void lookup_nick_it (void *cls,
401      const struct GNUNET_CRYPTO_EcdsaPrivateKey *private_key,
402      const char *label,
403      unsigned int rd_count,
404      const struct GNUNET_GNSRECORD_Data *rd)
405 {
406   struct GNUNET_GNSRECORD_Data **res = (cls);
407
408   int c;
409   if (0 != strcmp (label, GNUNET_GNS_MASTERZONE_STR))
410   {
411     GNUNET_break (0);
412     return;
413   }
414   for (c = 0; c < rd_count; c++)
415   {
416     if (GNUNET_GNSRECORD_TYPE_NICK == rd[c].record_type)
417     {
418       (*res) = GNUNET_malloc (rd[c].data_size + sizeof (struct GNUNET_GNSRECORD_Data));
419       (*res)->data = &(*res)[1];
420       memcpy ((char *)(*res)->data, rd[c].data, rd[c].data_size);
421       (*res)->data_size = rd[c].data_size;
422       (*res)->expiration_time = rd[c].expiration_time;
423       (*res)->flags = rd[c].flags;
424       (*res)->record_type = GNUNET_GNSRECORD_TYPE_NICK;
425       return;
426     }
427   }
428   (*res) = NULL;
429 }
430
431
432 static struct GNUNET_GNSRECORD_Data *
433 get_nick_record (const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone)
434 {
435   struct GNUNET_CRYPTO_EcdsaPublicKey pub;
436   struct GNUNET_GNSRECORD_Data *nick;
437   int res;
438
439   res = GSN_database->lookup_records (GSN_database->cls, zone,
440       GNUNET_GNS_MASTERZONE_STR, &lookup_nick_it, &nick);
441
442   if ((NULL == nick) || (GNUNET_OK != res))
443   {
444     GNUNET_CRYPTO_ecdsa_key_get_public (zone, &pub);
445     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "No nick name set for zone `%s'\n",
446         GNUNET_CRYPTO_ecdsa_public_key_to_string (&pub));
447     return NULL;
448   }
449
450   return nick;
451 }
452
453
454 static void merge_records (unsigned int rdc1,
455                            const struct GNUNET_GNSRECORD_Data *rd1,
456                            unsigned int rdc2,
457                            const struct GNUNET_GNSRECORD_Data *rd2,
458                            unsigned int *rdc_res,
459                            struct GNUNET_GNSRECORD_Data **rd_res)
460 {
461   int c;
462   size_t req;
463   char *data;
464   int record_offset;
465   size_t data_offset;
466   (*rdc_res) = rdc1 + rdc2;
467
468   if (0 == rdc1 + rdc2)
469   {
470     (*rd_res) = NULL;
471     return;
472   }
473
474   req = 0;
475   for (c=0; c< rdc1; c++)
476     req += sizeof (struct GNUNET_GNSRECORD_Data) + rd1[c].data_size;
477   for (c=0; c< rdc2; c++)
478     req += sizeof (struct GNUNET_GNSRECORD_Data) + rd2[c].data_size;
479   (*rd_res) = GNUNET_malloc (req);
480   data = (char *) &(*rd_res)[rdc1 + rdc2];
481   data_offset = 0;
482
483   for (c=0; c< rdc1; c++)
484   {
485     (*rd_res)[c] = rd1[c];
486     (*rd_res)[c].data = (void *) &data[data_offset];
487     memcpy ((void *) (*rd_res)[c].data, rd1[c].data, rd1[c].data_size);
488     data_offset += (*rd_res)[c].data_size;
489   }
490   record_offset = rdc1;
491   for (c=0; c< rdc2; c++)
492   {
493     (*rd_res)[c+record_offset] = rd2[c];
494     (*rd_res)[c+record_offset].data = (void *) &data[data_offset];
495     memcpy ((void *) (*rd_res)[c+record_offset].data, rd2[c].data, rd2[c].data_size);
496     data_offset += (*rd_res)[c+record_offset].data_size;
497   }
498   GNUNET_assert (req == (sizeof (struct GNUNET_GNSRECORD_Data)) * (*rdc_res) + data_offset);
499 }
500
501
502
503 /**
504  * Generate a 'struct LookupNameResponseMessage' and send it to the
505  * given client using the given notification context.
506  *
507  * @param nc notification context to use
508  * @param client client to unicast to
509  * @param request_id request ID to use
510  * @param zone_key zone key of the zone
511  * @param name name
512  * @param rd_count number of records in @a rd
513  * @param rd array of records
514  */
515 static void
516 send_lookup_response (struct GNUNET_SERVER_NotificationContext *nc,
517                       struct GNUNET_SERVER_Client *client,
518                       uint32_t request_id,
519                       const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
520                       const char *name,
521                       unsigned int rd_count,
522                       const struct GNUNET_GNSRECORD_Data *rd)
523 {
524   struct RecordResultMessage *zir_msg;
525   struct GNUNET_GNSRECORD_Data *nick;
526   struct GNUNET_GNSRECORD_Data *res;
527   unsigned int res_count;
528   size_t name_len;
529   size_t rd_ser_len;
530   size_t msg_size;
531   char *name_tmp;
532   char *rd_ser;
533
534   nick = get_nick_record (zone_key);
535   if ((NULL != nick) && (0 != strcmp(name, GNUNET_GNS_MASTERZONE_STR)))
536   {
537     nick->flags = (nick->flags | GNUNET_GNSRECORD_RF_PRIVATE) ^ GNUNET_GNSRECORD_RF_PRIVATE;
538     merge_records (rd_count,rd, 1, nick, &res_count, &res);
539     GNUNET_free (nick);
540   }
541   else
542   {
543     res_count = rd_count;
544     res = (struct GNUNET_GNSRECORD_Data *) rd;
545   }
546
547   name_len = strlen (name) + 1;
548   rd_ser_len = GNUNET_GNSRECORD_records_get_size (res_count, res);
549   msg_size = sizeof (struct RecordResultMessage) + name_len + rd_ser_len;
550   (void) client_lookup (client);
551   zir_msg = GNUNET_malloc (msg_size);
552   zir_msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT);
553   zir_msg->gns_header.header.size = htons (msg_size);
554   zir_msg->gns_header.r_id = htonl (request_id);
555   zir_msg->name_len = htons (name_len);
556   zir_msg->rd_count = htons (res_count);
557   zir_msg->rd_len = htons (rd_ser_len);
558   zir_msg->private_key = *zone_key;
559   name_tmp = (char *) &zir_msg[1];
560   memcpy (name_tmp, name, name_len);
561   rd_ser = &name_tmp[name_len];
562   GNUNET_GNSRECORD_records_serialize (res_count, res, rd_ser_len, rd_ser);
563   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
564               "Sending `%s' message with %u records and size %u\n",
565               "RECORD_RESULT",
566               rd_count,
567               msg_size);
568   GNUNET_SERVER_notification_context_unicast (nc,
569                                               client,
570                                               &zir_msg->gns_header.header,
571                                               GNUNET_NO);
572   if (rd != res)
573     GNUNET_free (res);
574   GNUNET_free (zir_msg);
575 }
576
577
578 /**
579  * Send response to the store request to the client.
580  *
581  * @param client client to talk to
582  * @param res status of the operation
583  * @param rid client's request ID
584  */
585 static void
586 send_store_response (struct GNUNET_SERVER_Client *client,
587                      int res,
588                      uint32_t rid)
589 {
590   struct RecordStoreResponseMessage rcr_msg;
591
592   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
593               "Sending `%s' message\n",
594               "RECORD_STORE_RESPONSE");
595   rcr_msg.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE_RESPONSE);
596   rcr_msg.gns_header.header.size = htons (sizeof (struct RecordStoreResponseMessage));
597   rcr_msg.gns_header.r_id = htonl (rid);
598   rcr_msg.op_result = htonl (res);
599   GNUNET_SERVER_notification_context_unicast (snc, client,
600                                               &rcr_msg.gns_header.header,
601                                               GNUNET_NO);
602 }
603
604
605 /**
606  * Cache operation complete, clean up.
607  *
608  * @param cls the `struct CacheOperation`
609  * @param success success
610  * @param emsg error messages
611  */
612 static void
613 finish_cache_operation (void *cls,
614                         int32_t success,
615                         const char *emsg)
616 {
617   struct CacheOperation *cop = cls;
618
619   if (NULL != emsg)
620     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
621                 _("Failed to replicate block in namecache: %s\n"),
622                 emsg);
623   else
624     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
625                 "CACHE operation completed\n");
626   GNUNET_CONTAINER_DLL_remove (cop_head,
627                                cop_tail,
628                                cop);
629   if (NULL != cop->client)
630     send_store_response (cop->client,
631                          success,
632                          cop->rid);
633   GNUNET_free (cop);
634 }
635
636
637 /**
638  * We just touched the plaintext information about a name in our zone;
639  * refresh the corresponding (encrypted) block in the namestore.
640  *
641  * @param client client responsible for the request
642  * @param rid request ID of the client
643  * @param zone_key private key of the zone
644  * @param name label for the records
645  * @param rd_count number of records
646  * @param rd records stored under the given @a name
647  */
648 static void
649 refresh_block (struct GNUNET_SERVER_Client *client,
650                uint32_t rid,
651                const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
652                const char *name,
653                unsigned int rd_count,
654                const struct GNUNET_GNSRECORD_Data *rd)
655 {
656   struct GNUNET_GNSRECORD_Block *block;
657   struct CacheOperation *cop;
658   struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
659
660   if (0 == rd_count)
661     block = GNUNET_GNSRECORD_block_create (zone_key,
662                                            GNUNET_TIME_UNIT_ZERO_ABS,
663                                            name,
664                                            rd, rd_count);
665   else
666     block = GNUNET_GNSRECORD_block_create (zone_key,
667                                            GNUNET_GNSRECORD_record_get_expiration_time (rd_count,
668                                                                                         rd),
669                                            name,
670                                            rd, rd_count);
671   GNUNET_assert (NULL != block);
672   GNUNET_CRYPTO_ecdsa_key_get_public (zone_key,
673                                       &pkey);
674   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
675               "Caching block for label `%s' in zone `%s' in namecache\n",
676               name,
677               GNUNET_GNSRECORD_z2s (&pkey));
678   cop = GNUNET_new (struct CacheOperation);
679   cop->client = client;
680   cop->rid = rid;
681   GNUNET_CONTAINER_DLL_insert (cop_head,
682                                cop_tail,
683                                cop);
684   cop->qe = GNUNET_NAMECACHE_block_cache (namecache,
685                                           block,
686                                           &finish_cache_operation,
687                                           cop);
688   GNUNET_free (block);
689 }
690
691
692 struct RecordLookupContext
693 {
694   const char *label;
695
696   int found;
697
698   unsigned int res_rd_count;
699
700   size_t rd_ser_len;
701
702   char *res_rd;
703
704   struct GNUNET_GNSRECORD_Data *nick;
705 };
706
707
708
709 static void
710 lookup_it (void *cls, const struct GNUNET_CRYPTO_EcdsaPrivateKey *private_key,
711     const char *label, unsigned int rd_count,
712     const struct GNUNET_GNSRECORD_Data *rd)
713 {
714   struct RecordLookupContext *rlc = cls;
715   struct GNUNET_GNSRECORD_Data *rd_res;
716   unsigned int rdc_res;
717
718   if (0 == strcmp (label, rlc->label))
719   {
720     rlc->found = GNUNET_YES;
721     if (0 != rd_count)
722     {
723       if ((NULL != rlc->nick) && (0 != strcmp(label, GNUNET_GNS_MASTERZONE_STR)))
724       {
725         /* Merge */
726         rd_res = NULL;
727         rdc_res = 0;
728         rlc->nick->flags = (rlc->nick->flags | GNUNET_GNSRECORD_RF_PRIVATE) ^ GNUNET_GNSRECORD_RF_PRIVATE;
729         merge_records (rd_count, rd,
730                        1, rlc->nick,
731                        &rdc_res, &rd_res);
732
733         rlc->rd_ser_len = GNUNET_GNSRECORD_records_get_size (rdc_res, rd_res);
734         rlc->res_rd_count = rdc_res;
735         rlc->res_rd = GNUNET_malloc (rlc->rd_ser_len);
736         GNUNET_GNSRECORD_records_serialize (rdc_res, rd_res, rlc->rd_ser_len , rlc->res_rd);
737
738         GNUNET_free  (rd_res);
739         GNUNET_free  (rlc->nick);
740         rlc->nick = NULL;
741       }
742       else
743       {
744         rlc->rd_ser_len = GNUNET_GNSRECORD_records_get_size (rd_count, rd);
745         rlc->res_rd_count = rd_count;
746         rlc->res_rd = GNUNET_malloc (rlc->rd_ser_len);
747         GNUNET_GNSRECORD_records_serialize (rd_count, rd, rlc->rd_ser_len , rlc->res_rd);
748       }
749     }
750     else
751     {
752       rlc->rd_ser_len = 0;
753       rlc->res_rd_count = 0;
754       rlc->res_rd = NULL;
755     }
756   }
757 }
758
759
760
761
762
763 /**
764  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_LOOKUP message
765  *
766  * @param cls unused
767  * @param client client sending the message
768  * @param message message of type 'struct RecordCreateMessage'
769  */
770 static void
771 handle_record_lookup (void *cls,
772                      struct GNUNET_SERVER_Client *client,
773                      const struct GNUNET_MessageHeader *message)
774 {
775   const struct LabelLookupMessage *ll_msg;
776   struct LabelLookupResponseMessage *llr_msg;
777   struct RecordLookupContext rlc;
778   const char *name_tmp;
779   char *res_name;
780   uint32_t name_len;
781   size_t src_size;
782   size_t res_size;
783   int res;
784
785   if (ntohs (message->size) < sizeof (struct LabelLookupMessage))
786   {
787     GNUNET_break (0);
788     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
789     return;
790   }
791
792   ll_msg = (const struct LabelLookupMessage *) message;
793   name_len = ntohl (ll_msg->label_len);
794   src_size = ntohs (message->size);
795
796   if (name_len !=  src_size - sizeof (struct LabelLookupMessage))
797   {
798     GNUNET_break (0);
799     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
800     return;
801   }
802
803   name_tmp = (const char *) &ll_msg[1];
804   if ('\0' != name_tmp[name_len -1])
805   {
806     GNUNET_break (0);
807     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
808     return;
809   }
810
811   GNUNET_SERVER_receive_done (client, GNUNET_OK);
812   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
813               "Received `%s' message for name `%s'\n",
814               "NAMESTORE_RECORD_LOOKUP", name_tmp);
815
816   if (NULL == (client_lookup (client)))
817   {
818     GNUNET_break (0);
819     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
820     return;
821   }
822
823   rlc.label = name_tmp;
824   rlc.found = GNUNET_NO;
825   rlc.res_rd_count = 0;
826   rlc.res_rd = NULL;
827   rlc.rd_ser_len = 0;
828   rlc.nick = get_nick_record (&ll_msg->zone);
829
830   res = GSN_database->lookup_records (GSN_database->cls,
831         &ll_msg->zone, name_tmp, &lookup_it, &rlc);
832
833   res_size = sizeof (struct LabelLookupResponseMessage) + name_len + rlc.rd_ser_len;
834   llr_msg = GNUNET_malloc (res_size);
835   llr_msg->gns_header.header.size = htons (res_size);
836   llr_msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_LOOKUP_RESPONSE);
837   llr_msg->gns_header.r_id = ll_msg->gns_header.r_id;
838   llr_msg->private_key = ll_msg->zone;
839   llr_msg->name_len = htons (name_len);
840   llr_msg->rd_count = htons (rlc.res_rd_count);
841   llr_msg->rd_len = htons (rlc.rd_ser_len);
842   res_name = (char *) &llr_msg[1];
843   if  ((GNUNET_YES == rlc.found) && (GNUNET_OK == res))
844     llr_msg->found = ntohs (GNUNET_YES);
845   else
846     llr_msg->found = ntohs (GNUNET_NO);
847   memcpy (&llr_msg[1], name_tmp, name_len);
848   memcpy (&res_name[name_len], rlc.res_rd, rlc.rd_ser_len);
849
850   GNUNET_SERVER_notification_context_unicast (snc, client, &llr_msg->gns_header.header,
851       GNUNET_NO);
852
853   GNUNET_free_non_null (rlc.res_rd);
854   GNUNET_free (llr_msg);
855 }
856
857
858 /**
859  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE message
860  *
861  * @param cls unused
862  * @param client client sending the message
863  * @param message message of type 'struct RecordCreateMessage'
864  */
865 static void
866 handle_record_store (void *cls,
867                      struct GNUNET_SERVER_Client *client,
868                      const struct GNUNET_MessageHeader *message)
869 {
870   const struct RecordStoreMessage *rp_msg;
871   size_t name_len;
872   size_t msg_size;
873   size_t msg_size_exp;
874   size_t rd_ser_len;
875   uint32_t rid;
876   const char *name_tmp;
877   char *conv_name;
878   const char *rd_ser;
879   unsigned int rd_count;
880   int res;
881   struct GNUNET_CRYPTO_EcdsaPublicKey pubkey;
882   struct ZoneMonitor *zm;
883
884   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
885               "Received `%s' message\n",
886               "NAMESTORE_RECORD_STORE");
887   if (ntohs (message->size) < sizeof (struct RecordStoreMessage))
888   {
889     GNUNET_break (0);
890     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
891     return;
892   }
893   rp_msg = (const struct RecordStoreMessage *) message;
894   rid = ntohl (rp_msg->gns_header.r_id);
895   name_len = ntohs (rp_msg->name_len);
896   msg_size = ntohs (message->size);
897   rd_count = ntohs (rp_msg->rd_count);
898   rd_ser_len = ntohs (rp_msg->rd_len);
899   GNUNET_break (0 == ntohs (rp_msg->reserved));
900   msg_size_exp = sizeof (struct RecordStoreMessage) + name_len + rd_ser_len;
901   if (msg_size != msg_size_exp)
902   {
903     GNUNET_break (0);
904     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
905     return;
906   }
907   if ((0 == name_len) || (name_len > MAX_NAME_LEN))
908   {
909     GNUNET_break (0);
910     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
911     return;
912   }
913   name_tmp = (const char *) &rp_msg[1];
914   rd_ser = &name_tmp[name_len];
915   if ('\0' != name_tmp[name_len -1])
916   {
917     GNUNET_break (0);
918     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
919     return;
920   }
921   (void) client_lookup (client);
922   {
923     struct GNUNET_GNSRECORD_Data rd[rd_count];
924
925     if (GNUNET_OK !=
926         GNUNET_GNSRECORD_records_deserialize (rd_ser_len, rd_ser, rd_count, rd))
927     {
928       GNUNET_break (0);
929       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
930       return;
931     }
932
933     /* Extracting and converting private key */
934     GNUNET_CRYPTO_ecdsa_key_get_public (&rp_msg->private_key,
935                                       &pubkey);
936     conv_name = GNUNET_GNSRECORD_string_to_lowercase (name_tmp);
937     if (NULL == conv_name)
938     {
939       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
940                   "Error converting name `%s'\n", name_tmp);
941       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
942       return;
943     }
944     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
945                 "Creating %u records for name `%s' in zone `%s'\n",
946                 (unsigned int) rd_count,
947                 conv_name,
948                 GNUNET_GNSRECORD_z2s (&pubkey));
949
950     if ( (0 == rd_count) &&
951          (GNUNET_NO ==
952           GSN_database->iterate_records (GSN_database->cls,
953                                          &rp_msg->private_key, 0, NULL, 0)) )
954     {
955       /* This name does not exist, so cannot be removed */
956       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
957                   "Name `%s' does not exist, no deletion required\n",
958                   conv_name);
959       res = GNUNET_NO;
960     }
961     else
962     {
963       res = GSN_database->store_records (GSN_database->cls,
964                                          &rp_msg->private_key,
965                                          conv_name,
966                                          rd_count, rd);
967       if (GNUNET_OK == res)
968       {
969         for (zm = monitor_head; NULL != zm; zm = zm->next)
970         {
971           if ( (0 == memcmp (&rp_msg->private_key, &zm->zone,
972                              sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey))) ||
973                (0 == memcmp (&zm->zone,
974                              &zero,
975                              sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey))) )
976           {
977             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
978                         "Notifying monitor about changes under label `%s'\n",
979                         conv_name);
980             send_lookup_response (monitor_nc,
981                                   zm->nc->client,
982                                   0,
983                                   &rp_msg->private_key,
984                                   conv_name,
985                                   rd_count, rd);
986           }
987           else
988             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
989                         "Monitor is for another zone\n");
990         }
991         if (NULL == monitor_head)
992           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
993                       "No monitors active\n");
994       }
995       else
996       {
997         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
998                     "Error storing record: %d\n",
999                     res);
1000       }
1001     }
1002     if (GNUNET_OK == res)
1003     {
1004       refresh_block (client, rid,
1005                      &rp_msg->private_key,
1006                      conv_name,
1007                      rd_count, rd);
1008       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1009       GNUNET_free (conv_name);
1010       return;
1011     }
1012     GNUNET_free (conv_name);
1013   }
1014   send_store_response (client, res, rid);
1015   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1016 }
1017
1018
1019 /**
1020  * Context for record remove operations passed from #handle_zone_to_name to
1021  * #handle_zone_to_name_it as closure
1022  */
1023 struct ZoneToNameCtx
1024 {
1025   /**
1026    * Namestore client
1027    */
1028   struct NamestoreClient *nc;
1029
1030   /**
1031    * Request id (to be used in the response to the client).
1032    */
1033   uint32_t rid;
1034
1035   /**
1036    * Set to #GNUNET_OK on success, #GNUNET_SYSERR on error.  Note that
1037    * not finding a name for the zone still counts as a 'success' here,
1038    * as this field is about the success of executing the IPC protocol.
1039    */
1040   int success;
1041 };
1042
1043
1044 /**
1045  * Zone to name iterator
1046  *
1047  * @param cls struct ZoneToNameCtx *
1048  * @param zone_key the zone key
1049  * @param name name
1050  * @param rd_count number of records in @a rd
1051  * @param rd record data
1052  */
1053 static void
1054 handle_zone_to_name_it (void *cls,
1055                         const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
1056                         const char *name,
1057                         unsigned int rd_count,
1058                         const struct GNUNET_GNSRECORD_Data *rd)
1059 {
1060   struct ZoneToNameCtx *ztn_ctx = cls;
1061   struct ZoneToNameResponseMessage *ztnr_msg;
1062   int16_t res;
1063   size_t name_len;
1064   size_t rd_ser_len;
1065   size_t msg_size;
1066   char *name_tmp;
1067   char *rd_tmp;
1068
1069   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1070               "Found result for zone-to-name lookup: `%s'\n",
1071               name);
1072   res = GNUNET_YES;
1073   name_len = (NULL == name) ? 0 : strlen (name) + 1;
1074   rd_ser_len = GNUNET_GNSRECORD_records_get_size (rd_count, rd);
1075   msg_size = sizeof (struct ZoneToNameResponseMessage) + name_len + rd_ser_len;
1076   if (msg_size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1077   {
1078     GNUNET_break (0);
1079     ztn_ctx->success = GNUNET_SYSERR;
1080     return;
1081   }
1082   ztnr_msg = GNUNET_malloc (msg_size);
1083   ztnr_msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME_RESPONSE);
1084   ztnr_msg->gns_header.header.size = htons (msg_size);
1085   ztnr_msg->gns_header.r_id = htonl (ztn_ctx->rid);
1086   ztnr_msg->res = htons (res);
1087   ztnr_msg->rd_len = htons (rd_ser_len);
1088   ztnr_msg->rd_count = htons (rd_count);
1089   ztnr_msg->name_len = htons (name_len);
1090   ztnr_msg->zone = *zone_key;
1091   name_tmp = (char *) &ztnr_msg[1];
1092   if (NULL != name)
1093     memcpy (name_tmp, name, name_len);
1094   rd_tmp = &name_tmp[name_len];
1095   GNUNET_GNSRECORD_records_serialize (rd_count, rd, rd_ser_len, rd_tmp);
1096   ztn_ctx->success = GNUNET_OK;
1097   GNUNET_SERVER_notification_context_unicast (snc, ztn_ctx->nc->client,
1098                                               &ztnr_msg->gns_header.header,
1099                                               GNUNET_NO);
1100   GNUNET_free (ztnr_msg);
1101 }
1102
1103
1104 /**
1105  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME message
1106  *
1107  * @param cls unused
1108  * @param client client sending the message
1109  * @param message message of type 'struct ZoneToNameMessage'
1110  */
1111 static void
1112 handle_zone_to_name (void *cls,
1113                      struct GNUNET_SERVER_Client *client,
1114                      const struct GNUNET_MessageHeader *message)
1115 {
1116   struct NamestoreClient *nc;
1117   const struct ZoneToNameMessage *ztn_msg;
1118   struct ZoneToNameCtx ztn_ctx;
1119   struct ZoneToNameResponseMessage ztnr_msg;
1120
1121   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1122               "Received `%s' message\n",
1123               "ZONE_TO_NAME");
1124   ztn_msg = (const struct ZoneToNameMessage *) message;
1125   nc = client_lookup (client);
1126   ztn_ctx.rid = ntohl (ztn_msg->gns_header.r_id);
1127   ztn_ctx.nc = nc;
1128   ztn_ctx.success = GNUNET_NO;
1129   if (GNUNET_SYSERR ==
1130       GSN_database->zone_to_name (GSN_database->cls,
1131                                   &ztn_msg->zone,
1132                                   &ztn_msg->value_zone,
1133                                   &handle_zone_to_name_it, &ztn_ctx))
1134   {
1135     /* internal error, hang up instead of signalling something
1136        that might be wrong */
1137     GNUNET_break (0);
1138     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1139     return;
1140   }
1141   if (GNUNET_NO == ztn_ctx.success)
1142   {
1143     /* no result found, send empty response */
1144     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1145                 "Found no result for zone-to-name lookup.\n");
1146     memset (&ztnr_msg, 0, sizeof (ztnr_msg));
1147     ztnr_msg.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME_RESPONSE);
1148     ztnr_msg.gns_header.header.size = htons (sizeof (ztnr_msg));
1149     ztnr_msg.gns_header.r_id = ztn_msg->gns_header.r_id;
1150     ztnr_msg.res = htons (GNUNET_NO);
1151     GNUNET_SERVER_notification_context_unicast (snc,
1152                                                 client,
1153                                                 &ztnr_msg.gns_header.header,
1154                                                 GNUNET_NO);
1155   }
1156   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1157 }
1158
1159
1160 /**
1161  * Zone iteration processor result
1162  */
1163 enum ZoneIterationResult
1164 {
1165   /**
1166    * Iteration start.
1167    */
1168   IT_START = 0,
1169
1170   /**
1171    * Found records,
1172    * Continue to iterate with next iteration_next call
1173    */
1174   IT_SUCCESS_MORE_AVAILABLE = 1,
1175
1176   /**
1177    * Iteration complete
1178    */
1179   IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE = 2
1180 };
1181
1182
1183 /**
1184  * Context for record remove operations passed from
1185  * #run_zone_iteration_round to #zone_iterate_proc as closure
1186  */
1187 struct ZoneIterationProcResult
1188 {
1189   /**
1190    * The zone iteration handle
1191    */
1192   struct ZoneIteration *zi;
1193
1194   /**
1195    * Iteration result: iteration done?
1196    * #IT_SUCCESS_MORE_AVAILABLE:  if there may be more results overall but
1197    * we got one for now and have sent it to the client
1198    * #IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE: if there are no further results,
1199    * #IT_START: if we are still trying to find a result.
1200    */
1201   int res_iteration_finished;
1202
1203 };
1204
1205
1206 /**
1207  * Process results for zone iteration from database
1208  *
1209  * @param cls struct ZoneIterationProcResult *proc
1210  * @param zone_key the zone key
1211  * @param name name
1212  * @param rd_count number of records for this name
1213  * @param rd record data
1214  */
1215 static void
1216 zone_iterate_proc (void *cls,
1217                        const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
1218                        const char *name,
1219                        unsigned int rd_count,
1220                        const struct GNUNET_GNSRECORD_Data *rd)
1221 {
1222   struct ZoneIterationProcResult *proc = cls;
1223   unsigned int i;
1224   int do_refresh_block;
1225
1226   if ((NULL == zone_key) && (NULL == name))
1227   {
1228     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1229                 "Iteration done\n");
1230     proc->res_iteration_finished = IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE;
1231     return;
1232   }
1233   if ((NULL == zone_key) || (NULL == name))
1234   {
1235     /* what is this!? should never happen */
1236     proc->res_iteration_finished = IT_START;
1237     GNUNET_break (0);
1238     return;
1239   }
1240   proc->res_iteration_finished = IT_SUCCESS_MORE_AVAILABLE;
1241   send_lookup_response (snc,
1242                         proc->zi->client->client,
1243                         proc->zi->request_id,
1244                         zone_key,
1245                         name,
1246                         rd_count,
1247                         rd);
1248   do_refresh_block = GNUNET_NO;
1249   for (i=0;i<rd_count;i++)
1250     if(  (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION)) &&
1251          (0 == (rd[i].flags & GNUNET_GNSRECORD_RF_PENDING)) )
1252     {
1253       do_refresh_block = GNUNET_YES;
1254       break;
1255     }
1256   if (GNUNET_YES == do_refresh_block)
1257     refresh_block (NULL, 0,
1258                    zone_key,
1259                    name,
1260                    rd_count,
1261                    rd);
1262
1263 }
1264
1265
1266 /**
1267  * Perform the next round of the zone iteration.
1268  *
1269  * @param zi zone iterator to process
1270  */
1271 static void
1272 run_zone_iteration_round (struct ZoneIteration *zi)
1273 {
1274   struct ZoneIterationProcResult proc;
1275   struct RecordResultMessage rrm;
1276   int ret;
1277
1278   memset (&proc, 0, sizeof (proc));
1279   proc.zi = zi;
1280   proc.res_iteration_finished = IT_START;
1281   while (IT_START == proc.res_iteration_finished)
1282   {
1283     if (GNUNET_SYSERR ==
1284         (ret = GSN_database->iterate_records (GSN_database->cls,
1285                                               (0 == memcmp (&zi->zone, &zero, sizeof (zero)))
1286                                               ? NULL
1287                                               : &zi->zone,
1288                                               zi->offset,
1289                                               &zone_iterate_proc, &proc)))
1290     {
1291       GNUNET_break (0);
1292       break;
1293     }
1294     if (GNUNET_NO == ret)
1295       proc.res_iteration_finished = IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE;
1296     zi->offset++;
1297   }
1298   if (IT_SUCCESS_MORE_AVAILABLE == proc.res_iteration_finished)
1299   {
1300     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1301                 "More results available\n");
1302     return; /* more results later */
1303   }
1304   /* send empty response to indicate end of list */
1305   memset (&rrm, 0, sizeof (rrm));
1306   rrm.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT);
1307   rrm.gns_header.header.size = htons (sizeof (rrm));
1308   rrm.gns_header.r_id = htonl (zi->request_id);
1309   GNUNET_SERVER_notification_context_unicast (snc,
1310                                               zi->client->client,
1311                                               &rrm.gns_header.header,
1312                                               GNUNET_NO);
1313   GNUNET_CONTAINER_DLL_remove (zi->client->op_head,
1314                                zi->client->op_tail,
1315                                zi);
1316   GNUNET_free (zi);
1317 }
1318
1319
1320 /**
1321  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_START message
1322  *
1323  * @param cls unused
1324  * @param client the client sending the message
1325  * @param message message of type 'struct ZoneIterationStartMessage'
1326  */
1327 static void
1328 handle_iteration_start (void *cls,
1329                         struct GNUNET_SERVER_Client *client,
1330                         const struct GNUNET_MessageHeader *message)
1331 {
1332   const struct ZoneIterationStartMessage *zis_msg;
1333   struct NamestoreClient *nc;
1334   struct ZoneIteration *zi;
1335
1336   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "ZONE_ITERATION_START");
1337   if (NULL == (nc = client_lookup (client)))
1338   {
1339     GNUNET_break (0);
1340     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1341     return;
1342   }
1343   zis_msg = (const struct ZoneIterationStartMessage *) message;
1344   zi = GNUNET_new (struct ZoneIteration);
1345   zi->request_id = ntohl (zis_msg->gns_header.r_id);
1346   zi->offset = 0;
1347   zi->client = nc;
1348   zi->zone = zis_msg->zone;
1349
1350
1351   GNUNET_CONTAINER_DLL_insert (nc->op_head, nc->op_tail, zi);
1352   run_zone_iteration_round (zi);
1353   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1354 }
1355
1356
1357 /**
1358  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_STOP message
1359  *
1360  * @param cls unused
1361  * @param client GNUNET_SERVER_Client sending the message
1362  * @param message message of type 'struct ZoneIterationStopMessage'
1363  */
1364 static void
1365 handle_iteration_stop (void *cls,
1366                        struct GNUNET_SERVER_Client *client,
1367                        const struct GNUNET_MessageHeader *message)
1368 {
1369   struct NamestoreClient *nc;
1370   struct ZoneIteration *zi;
1371   const struct ZoneIterationStopMessage *zis_msg;
1372   uint32_t rid;
1373
1374   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1375               "Received `%s' message\n",
1376               "ZONE_ITERATION_STOP");
1377   if (NULL == (nc = client_lookup(client)))
1378   {
1379     GNUNET_break (0);
1380     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1381     return;
1382   }
1383   zis_msg = (const struct ZoneIterationStopMessage *) message;
1384   rid = ntohl (zis_msg->gns_header.r_id);
1385   for (zi = nc->op_head; NULL != zi; zi = zi->next)
1386     if (zi->request_id == rid)
1387       break;
1388   if (NULL == zi)
1389   {
1390     GNUNET_break (0);
1391     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1392     return;
1393   }
1394   GNUNET_CONTAINER_DLL_remove (nc->op_head, nc->op_tail, zi);
1395   GNUNET_free (zi);
1396   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1397 }
1398
1399
1400 /**
1401  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_NEXT message
1402  *
1403  * @param cls unused
1404  * @param client GNUNET_SERVER_Client sending the message
1405  * @param message message of type 'struct ZoneIterationNextMessage'
1406  */
1407 static void
1408 handle_iteration_next (void *cls,
1409                        struct GNUNET_SERVER_Client *client,
1410                        const struct GNUNET_MessageHeader *message)
1411 {
1412   struct NamestoreClient *nc;
1413   struct ZoneIteration *zi;
1414   const struct ZoneIterationNextMessage *zis_msg;
1415   uint32_t rid;
1416
1417   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1418               "Received `%s' message\n",
1419               "ZONE_ITERATION_NEXT");
1420   if (NULL == (nc = client_lookup(client)))
1421   {
1422     GNUNET_break (0);
1423     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1424     return;
1425   }
1426   zis_msg = (const struct ZoneIterationNextMessage *) message;
1427   rid = ntohl (zis_msg->gns_header.r_id);
1428   for (zi = nc->op_head; NULL != zi; zi = zi->next)
1429     if (zi->request_id == rid)
1430       break;
1431   if (NULL == zi)
1432   {
1433     GNUNET_break (0);
1434     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1435     return;
1436   }
1437   run_zone_iteration_round (zi);
1438   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1439 }
1440
1441
1442 /**
1443  * Send 'sync' message to zone monitor, we're now in sync.
1444  *
1445  * @param zm monitor that is now in sync
1446  */
1447 static void
1448 monitor_sync (struct ZoneMonitor *zm)
1449 {
1450   struct GNUNET_MessageHeader sync;
1451
1452   sync.size = htons (sizeof (struct GNUNET_MessageHeader));
1453   sync.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_SYNC);
1454   GNUNET_SERVER_notification_context_unicast (monitor_nc,
1455                                               zm->nc->client,
1456                                               &sync,
1457                                               GNUNET_NO);
1458 }
1459
1460
1461 /**
1462  * Obtain the next datum during the zone monitor's zone intiial iteration.
1463  *
1464  * @param cls zone monitor that does its initial iteration
1465  * @param tc scheduler context
1466  */
1467 static void
1468 monitor_next (void *cls,
1469               const struct GNUNET_SCHEDULER_TaskContext *tc);
1470
1471
1472 /**
1473  * A #GNUNET_NAMESTORE_RecordIterator for monitors.
1474  *
1475  * @param cls a 'struct ZoneMonitor *' with information about the monitor
1476  * @param zone_key zone key of the zone
1477  * @param name name
1478  * @param rd_count number of records in @a rd
1479  * @param rd array of records
1480  */
1481 static void
1482 monitor_iterate_cb (void *cls,
1483                     const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
1484                     const char *name,
1485                     unsigned int rd_count,
1486                     const struct GNUNET_GNSRECORD_Data *rd)
1487 {
1488   struct ZoneMonitor *zm = cls;
1489
1490   if (NULL == name)
1491   {
1492     /* finished with iteration */
1493     monitor_sync (zm);
1494     return;
1495   }
1496   send_lookup_response (monitor_nc,
1497                         zm->nc->client,
1498                         0,
1499                         zone_key,
1500                         name,
1501                         rd_count,
1502                         rd);
1503   zm->task = GNUNET_SCHEDULER_add_now (&monitor_next, zm);
1504 }
1505
1506
1507 /**
1508  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_START message
1509  *
1510  * @param cls unused
1511  * @param client the client sending the message
1512  * @param message message of type 'struct ZoneMonitorStartMessage'
1513  */
1514 static void
1515 handle_monitor_start (void *cls,
1516                       struct GNUNET_SERVER_Client *client,
1517                       const struct GNUNET_MessageHeader *message)
1518 {
1519   const struct ZoneMonitorStartMessage *zis_msg;
1520   struct ZoneMonitor *zm;
1521
1522   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1523               "Received `%s' message\n",
1524               "ZONE_MONITOR_START");
1525   zis_msg = (const struct ZoneMonitorStartMessage *) message;
1526   zm = GNUNET_new (struct ZoneMonitor);
1527   zm->offset = 0;
1528   zm->nc = client_lookup (client);
1529   zm->zone = zis_msg->zone;
1530   GNUNET_CONTAINER_DLL_insert (monitor_head, monitor_tail, zm);
1531   GNUNET_SERVER_client_mark_monitor (client);
1532   GNUNET_SERVER_disable_receive_done_warning (client);
1533   GNUNET_SERVER_notification_context_add (monitor_nc,
1534                                           client);
1535   if (GNUNET_YES == ntohl (zis_msg->iterate_first))
1536     zm->task = GNUNET_SCHEDULER_add_now (&monitor_next, zm);
1537   else
1538     monitor_sync (zm);
1539 }
1540
1541
1542 /**
1543  * Obtain the next datum during the zone monitor's zone intiial iteration.
1544  *
1545  * @param cls zone monitor that does its initial iteration
1546  * @param tc scheduler context
1547  */
1548 static void
1549 monitor_next (void *cls,
1550               const struct GNUNET_SCHEDULER_TaskContext *tc)
1551 {
1552   struct ZoneMonitor *zm = cls;
1553   int ret;
1554
1555   zm->task = GNUNET_SCHEDULER_NO_TASK;
1556   ret = GSN_database->iterate_records (GSN_database->cls,
1557                                        (0 == memcmp (&zm->zone, &zero, sizeof (zero)))
1558                                        ? NULL
1559                                        : &zm->zone,
1560                                        zm->offset++,
1561                                        &monitor_iterate_cb, zm);
1562   if (GNUNET_SYSERR == ret)
1563   {
1564     GNUNET_SERVER_client_disconnect (zm->nc->client);
1565     return;
1566   }
1567   if (GNUNET_NO == ret)
1568   {
1569     /* empty zone */
1570     monitor_sync (zm);
1571     return;
1572   }
1573 }
1574
1575
1576 /**
1577  * Process namestore requests.
1578  *
1579  * @param cls closure
1580  * @param server the initialized server
1581  * @param cfg configuration to use
1582  */
1583 static void
1584 run (void *cls, struct GNUNET_SERVER_Handle *server,
1585      const struct GNUNET_CONFIGURATION_Handle *cfg)
1586 {
1587   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1588     {&handle_record_store, NULL,
1589      GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE, 0},
1590     {&handle_record_lookup, NULL,
1591      GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_LOOKUP, 0},
1592     {&handle_zone_to_name, NULL,
1593      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME, sizeof (struct ZoneToNameMessage) },
1594     {&handle_iteration_start, NULL,
1595      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_START, sizeof (struct ZoneIterationStartMessage) },
1596     {&handle_iteration_next, NULL,
1597      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_NEXT, sizeof (struct ZoneIterationNextMessage) },
1598     {&handle_iteration_stop, NULL,
1599      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_STOP, sizeof (struct ZoneIterationStopMessage) },
1600     {&handle_monitor_start, NULL,
1601      GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_START, sizeof (struct ZoneMonitorStartMessage) },
1602     {NULL, NULL, 0, 0}
1603   };
1604   char *database;
1605
1606   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting namestore service\n");
1607   GSN_cfg = cfg;
1608   monitor_nc = GNUNET_SERVER_notification_context_create (server, 1);
1609   namecache = GNUNET_NAMECACHE_connect (cfg);
1610   /* Loading database plugin */
1611   if (GNUNET_OK !=
1612       GNUNET_CONFIGURATION_get_value_string (cfg, "namestore", "database",
1613                                              &database))
1614     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No database backend configured\n");
1615
1616   GNUNET_asprintf (&db_lib_name, "libgnunet_plugin_namestore_%s", database);
1617   GSN_database = GNUNET_PLUGIN_load (db_lib_name, (void *) GSN_cfg);
1618   GNUNET_free (database);
1619   if (NULL == GSN_database)
1620   {
1621     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1622                 "Could not load database backend `%s'\n",
1623                 db_lib_name);
1624     GNUNET_SCHEDULER_add_now (&cleanup_task, NULL);
1625     return;
1626   }
1627
1628   /* Configuring server handles */
1629   GNUNET_SERVER_add_handlers (server, handlers);
1630   snc = GNUNET_SERVER_notification_context_create (server, 16);
1631   GNUNET_SERVER_disconnect_notify (server,
1632                                    &client_disconnect_notification,
1633                                    NULL);
1634   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleanup_task,
1635                                 NULL);
1636 }
1637
1638
1639 /**
1640  * The main function for the template service.
1641  *
1642  * @param argc number of arguments from the command line
1643  * @param argv command line arguments
1644  * @return 0 ok, 1 on error
1645  */
1646 int
1647 main (int argc, char *const *argv)
1648 {
1649   return (GNUNET_OK ==
1650           GNUNET_SERVICE_run (argc, argv, "namestore",
1651                               GNUNET_SERVICE_OPTION_NONE, &run, NULL)) ? 0 : 1;
1652 }
1653
1654 /* end of gnunet-service-namestore.c */
1655