- log
[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
401 lookup_nick_it (void *cls,
402                 const struct GNUNET_CRYPTO_EcdsaPrivateKey *private_key,
403                 const char *label,
404                 unsigned int rd_count,
405                 const struct GNUNET_GNSRECORD_Data *rd)
406 {
407   struct GNUNET_GNSRECORD_Data **res = cls;
408   int c;
409
410   if (0 != strcmp (label, GNUNET_GNS_MASTERZONE_STR))
411   {
412     GNUNET_break (0);
413     return;
414   }
415   for (c = 0; c < rd_count; c++)
416   {
417     if (GNUNET_GNSRECORD_TYPE_NICK == rd[c].record_type)
418     {
419       (*res) = GNUNET_malloc (rd[c].data_size + sizeof (struct GNUNET_GNSRECORD_Data));
420       (*res)->data = &(*res)[1];
421       memcpy ((char *)(*res)->data, rd[c].data, rd[c].data_size);
422       (*res)->data_size = rd[c].data_size;
423       (*res)->expiration_time = rd[c].expiration_time;
424       (*res)->flags = rd[c].flags;
425       (*res)->record_type = GNUNET_GNSRECORD_TYPE_NICK;
426       return;
427     }
428   }
429   (*res) = NULL;
430 }
431
432
433 static struct GNUNET_GNSRECORD_Data *
434 get_nick_record (const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone)
435 {
436   struct GNUNET_CRYPTO_EcdsaPublicKey pub;
437   struct GNUNET_GNSRECORD_Data *nick;
438   int res;
439
440   res = GSN_database->lookup_records (GSN_database->cls, zone,
441                                       GNUNET_GNS_MASTERZONE_STR,
442                                       &lookup_nick_it, &nick);
443   if ((NULL == nick) || (GNUNET_OK != res))
444   {
445     GNUNET_CRYPTO_ecdsa_key_get_public (zone, &pub);
446     GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK,
447                 "No nick name set for zone `%s'\n",
448                 GNUNET_GNSRECORD_z2s (&pub));
449     return NULL;
450   }
451   return nick;
452 }
453
454
455 static void
456 merge_with_nick_records ( const struct GNUNET_GNSRECORD_Data *nick_rd,
457                           unsigned int rdc2,
458                           const struct GNUNET_GNSRECORD_Data *rd2,
459                           unsigned int *rdc_res,
460                           struct GNUNET_GNSRECORD_Data **rd_res)
461 {
462   uint64_t latest_expiration;
463   int c;
464   size_t req;
465   char *data;
466   int record_offset;
467   size_t data_offset;
468   (*rdc_res) = 1 + rdc2;
469
470   if (0 == 1 + rdc2)
471   {
472     (*rd_res) = NULL;
473     return;
474   }
475
476   req = 0;
477   for (c=0; c< 1; c++)
478     req += sizeof (struct GNUNET_GNSRECORD_Data) + nick_rd[c].data_size;
479   for (c=0; c< rdc2; c++)
480     req += sizeof (struct GNUNET_GNSRECORD_Data) + rd2[c].data_size;
481   (*rd_res) = GNUNET_malloc (req);
482   data = (char *) &(*rd_res)[1 + rdc2];
483   data_offset = 0;
484   latest_expiration = 0;
485
486   for (c=0; c< rdc2; c++)
487   {
488     if (0 != (rd2[c].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION))
489     {
490       if ((GNUNET_TIME_absolute_get().abs_value_us + rd2[c].expiration_time) >
491         latest_expiration)
492           latest_expiration = rd2[c].expiration_time;
493     }
494     else if (rd2[c].expiration_time > latest_expiration)
495       latest_expiration = rd2[c].expiration_time;
496     (*rd_res)[c] = rd2[c];
497     (*rd_res)[c].data = (void *) &data[data_offset];
498     memcpy ((void *) (*rd_res)[c].data, rd2[c].data, rd2[c].data_size);
499     data_offset += (*rd_res)[c].data_size;
500   }
501   record_offset = rdc2;
502   for (c=0; c< 1; c++)
503   {
504     (*rd_res)[c+record_offset] = nick_rd[c];
505     (*rd_res)[c+record_offset].expiration_time = latest_expiration;
506     (*rd_res)[c+record_offset].data = (void *) &data[data_offset];
507     memcpy ((void *) (*rd_res)[c+record_offset].data, nick_rd[c].data, nick_rd[c].data_size);
508     data_offset += (*rd_res)[c+record_offset].data_size;
509   }
510   GNUNET_assert (req == (sizeof (struct GNUNET_GNSRECORD_Data)) * (*rdc_res) + data_offset);
511 }
512
513
514 /**
515  * Generate a 'struct LookupNameResponseMessage' and send it to the
516  * given client using the given notification context.
517  *
518  * @param nc notification context to use
519  * @param client client to unicast to
520  * @param request_id request ID to use
521  * @param zone_key zone key of the zone
522  * @param name name
523  * @param rd_count number of records in @a rd
524  * @param rd array of records
525  */
526 static void
527 send_lookup_response (struct GNUNET_SERVER_NotificationContext *nc,
528                       struct GNUNET_SERVER_Client *client,
529                       uint32_t request_id,
530                       const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
531                       const char *name,
532                       unsigned int rd_count,
533                       const struct GNUNET_GNSRECORD_Data *rd)
534 {
535   struct RecordResultMessage *zir_msg;
536   struct GNUNET_GNSRECORD_Data *nick;
537   struct GNUNET_GNSRECORD_Data *res;
538   unsigned int res_count;
539   size_t name_len;
540   size_t rd_ser_len;
541   size_t msg_size;
542   char *name_tmp;
543   char *rd_ser;
544
545   nick = get_nick_record (zone_key);
546   if ((NULL != nick) && (0 != strcmp(name, GNUNET_GNS_MASTERZONE_STR)))
547   {
548     nick->flags = (nick->flags | GNUNET_GNSRECORD_RF_PRIVATE) ^ GNUNET_GNSRECORD_RF_PRIVATE;
549     merge_with_nick_records (nick, rd_count,rd, &res_count, &res);
550     //fprintf (stderr, "Merging %u records for `%s' with NICK records\n",rd_count, name);
551     GNUNET_free (nick);
552   }
553   else
554   {
555     res_count = rd_count;
556     res = (struct GNUNET_GNSRECORD_Data *) rd;
557     //fprintf (stderr, "Not merging %u records for `%s' with NICK records\n",rd_count, name);
558   }
559
560   name_len = strlen (name) + 1;
561   rd_ser_len = GNUNET_GNSRECORD_records_get_size (res_count, res);
562   msg_size = sizeof (struct RecordResultMessage) + name_len + rd_ser_len;
563   (void) client_lookup (client);
564   zir_msg = GNUNET_malloc (msg_size);
565   zir_msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT);
566   zir_msg->gns_header.header.size = htons (msg_size);
567   zir_msg->gns_header.r_id = htonl (request_id);
568   zir_msg->name_len = htons (name_len);
569   zir_msg->rd_count = htons (res_count);
570   zir_msg->rd_len = htons (rd_ser_len);
571   zir_msg->private_key = *zone_key;
572   name_tmp = (char *) &zir_msg[1];
573   memcpy (name_tmp, name, name_len);
574   rd_ser = &name_tmp[name_len];
575   GNUNET_GNSRECORD_records_serialize (res_count, res, rd_ser_len, rd_ser);
576   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
577               "Sending `%s' message with %u records and size %u\n",
578               "RECORD_RESULT",
579               res_count,
580               msg_size);
581   GNUNET_SERVER_notification_context_unicast (nc,
582                                               client,
583                                               &zir_msg->gns_header.header,
584                                               GNUNET_NO);
585   if (rd != res)
586     GNUNET_free (res);
587   GNUNET_free (zir_msg);
588 }
589
590
591 /**
592  * Send response to the store request to the client.
593  *
594  * @param client client to talk to
595  * @param res status of the operation
596  * @param rid client's request ID
597  */
598 static void
599 send_store_response (struct GNUNET_SERVER_Client *client,
600                      int res,
601                      uint32_t rid)
602 {
603   struct RecordStoreResponseMessage rcr_msg;
604
605   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
606               "Sending `%s' message\n",
607               "RECORD_STORE_RESPONSE");
608   rcr_msg.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE_RESPONSE);
609   rcr_msg.gns_header.header.size = htons (sizeof (struct RecordStoreResponseMessage));
610   rcr_msg.gns_header.r_id = htonl (rid);
611   rcr_msg.op_result = htonl (res);
612   GNUNET_SERVER_notification_context_unicast (snc, client,
613                                               &rcr_msg.gns_header.header,
614                                               GNUNET_NO);
615 }
616
617
618 /**
619  * Cache operation complete, clean up.
620  *
621  * @param cls the `struct CacheOperation`
622  * @param success success
623  * @param emsg error messages
624  */
625 static void
626 finish_cache_operation (void *cls,
627                         int32_t success,
628                         const char *emsg)
629 {
630   struct CacheOperation *cop = cls;
631
632   if (NULL != emsg)
633     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
634                 _("Failed to replicate block in namecache: %s\n"),
635                 emsg);
636   else
637     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
638                 "CACHE operation completed\n");
639   GNUNET_CONTAINER_DLL_remove (cop_head,
640                                cop_tail,
641                                cop);
642   if (NULL != cop->client)
643     send_store_response (cop->client,
644                          success,
645                          cop->rid);
646   GNUNET_free (cop);
647 }
648
649
650 /**
651  * We just touched the plaintext information about a name in our zone;
652  * refresh the corresponding (encrypted) block in the namecache.
653  *
654  * @param client client responsible for the request
655  * @param rid request ID of the client
656  * @param zone_key private key of the zone
657  * @param name label for the records
658  * @param rd_count number of records
659  * @param rd records stored under the given @a name
660  */
661 static void
662 refresh_block (struct GNUNET_SERVER_Client *client,
663                uint32_t rid,
664                const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
665                const char *name,
666                unsigned int rd_count,
667                const struct GNUNET_GNSRECORD_Data *rd)
668 {
669   struct GNUNET_GNSRECORD_Block *block;
670   struct CacheOperation *cop;
671   struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
672   struct GNUNET_GNSRECORD_Data *nick;
673   struct GNUNET_GNSRECORD_Data *res;
674   unsigned int res_count;
675
676   nick = get_nick_record (zone_key);
677   res_count = rd_count;
678   res = (struct GNUNET_GNSRECORD_Data *) rd; /* fixme: a bit unclean... */
679   if (NULL != nick)
680   {
681     nick->flags = (nick->flags | GNUNET_GNSRECORD_RF_PRIVATE) ^ GNUNET_GNSRECORD_RF_PRIVATE;
682     merge_with_nick_records (nick, rd_count,rd, &res_count, &res);
683     GNUNET_free (nick);
684   }
685
686   if (0 == res_count)
687     block = GNUNET_GNSRECORD_block_create (zone_key,
688                                            GNUNET_TIME_UNIT_ZERO_ABS,
689                                            name,
690                                            res, rd_count);
691   else
692     block = GNUNET_GNSRECORD_block_create (zone_key,
693                                            GNUNET_GNSRECORD_record_get_expiration_time (res_count,
694                                                res),
695                                            name,
696                                            res, res_count);
697   GNUNET_assert (NULL != block);
698   GNUNET_CRYPTO_ecdsa_key_get_public (zone_key,
699                                       &pkey);
700   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
701               "Caching block for label `%s' with %u records in zone `%s' in namecache\n",
702               name,
703               res_count,
704               GNUNET_GNSRECORD_z2s (&pkey));
705   cop = GNUNET_new (struct CacheOperation);
706   cop->client = client;
707   cop->rid = rid;
708   GNUNET_CONTAINER_DLL_insert (cop_head,
709                                cop_tail,
710                                cop);
711   cop->qe = GNUNET_NAMECACHE_block_cache (namecache,
712                                           block,
713                                           &finish_cache_operation,
714                                           cop);
715   GNUNET_free (block);
716 }
717
718
719 struct RecordLookupContext
720 {
721   const char *label;
722
723   int found;
724
725   unsigned int res_rd_count;
726
727   size_t rd_ser_len;
728
729   char *res_rd;
730
731   struct GNUNET_GNSRECORD_Data *nick;
732 };
733
734
735
736 static void
737 lookup_it (void *cls, const struct GNUNET_CRYPTO_EcdsaPrivateKey *private_key,
738     const char *label, unsigned int rd_count,
739     const struct GNUNET_GNSRECORD_Data *rd)
740 {
741   struct RecordLookupContext *rlc = cls;
742   struct GNUNET_GNSRECORD_Data *rd_res;
743   unsigned int rdc_res;
744
745   if (0 == strcmp (label, rlc->label))
746   {
747     rlc->found = GNUNET_YES;
748     if (0 != rd_count)
749     {
750       if ((NULL != rlc->nick) && (0 != strcmp(label, GNUNET_GNS_MASTERZONE_STR)))
751       {
752         /* Merge */
753         rd_res = NULL;
754         rdc_res = 0;
755         rlc->nick->flags = (rlc->nick->flags | GNUNET_GNSRECORD_RF_PRIVATE) ^ GNUNET_GNSRECORD_RF_PRIVATE;
756         merge_with_nick_records ( rlc->nick,
757                                   rd_count, rd,
758                                   &rdc_res, &rd_res);
759
760         rlc->rd_ser_len = GNUNET_GNSRECORD_records_get_size (rdc_res, rd_res);
761         rlc->res_rd_count = rdc_res;
762         rlc->res_rd = GNUNET_malloc (rlc->rd_ser_len);
763         GNUNET_GNSRECORD_records_serialize (rdc_res, rd_res, rlc->rd_ser_len , rlc->res_rd);
764
765         GNUNET_free  (rd_res);
766         GNUNET_free  (rlc->nick);
767         rlc->nick = NULL;
768       }
769       else
770       {
771         rlc->rd_ser_len = GNUNET_GNSRECORD_records_get_size (rd_count, rd);
772         rlc->res_rd_count = rd_count;
773         rlc->res_rd = GNUNET_malloc (rlc->rd_ser_len);
774         GNUNET_GNSRECORD_records_serialize (rd_count, rd, rlc->rd_ser_len , rlc->res_rd);
775       }
776     }
777     else
778     {
779       rlc->rd_ser_len = 0;
780       rlc->res_rd_count = 0;
781       rlc->res_rd = NULL;
782     }
783   }
784 }
785
786
787
788
789
790 /**
791  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_LOOKUP message
792  *
793  * @param cls unused
794  * @param client client sending the message
795  * @param message message of type 'struct RecordCreateMessage'
796  */
797 static void
798 handle_record_lookup (void *cls,
799                      struct GNUNET_SERVER_Client *client,
800                      const struct GNUNET_MessageHeader *message)
801 {
802   const struct LabelLookupMessage *ll_msg;
803   struct LabelLookupResponseMessage *llr_msg;
804   struct RecordLookupContext rlc;
805   const char *name_tmp;
806   char *res_name;
807   uint32_t name_len;
808   size_t src_size;
809   size_t res_size;
810   int res;
811
812   if (ntohs (message->size) < sizeof (struct LabelLookupMessage))
813   {
814     GNUNET_break (0);
815     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
816     return;
817   }
818
819   ll_msg = (const struct LabelLookupMessage *) message;
820   name_len = ntohl (ll_msg->label_len);
821   src_size = ntohs (message->size);
822
823   if (name_len !=  src_size - sizeof (struct LabelLookupMessage))
824   {
825     GNUNET_break (0);
826     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
827     return;
828   }
829
830   name_tmp = (const char *) &ll_msg[1];
831   if ('\0' != name_tmp[name_len -1])
832   {
833     GNUNET_break (0);
834     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
835     return;
836   }
837
838   GNUNET_SERVER_receive_done (client, GNUNET_OK);
839   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
840               "Received `%s' message for name `%s'\n",
841               "NAMESTORE_RECORD_LOOKUP", name_tmp);
842
843   if (NULL == (client_lookup (client)))
844   {
845     GNUNET_break (0);
846     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
847     return;
848   }
849
850   rlc.label = name_tmp;
851   rlc.found = GNUNET_NO;
852   rlc.res_rd_count = 0;
853   rlc.res_rd = NULL;
854   rlc.rd_ser_len = 0;
855   rlc.nick = get_nick_record (&ll_msg->zone);
856
857   res = GSN_database->lookup_records (GSN_database->cls,
858         &ll_msg->zone, name_tmp, &lookup_it, &rlc);
859
860   res_size = sizeof (struct LabelLookupResponseMessage) + name_len + rlc.rd_ser_len;
861   llr_msg = GNUNET_malloc (res_size);
862   llr_msg->gns_header.header.size = htons (res_size);
863   llr_msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_LOOKUP_RESPONSE);
864   llr_msg->gns_header.r_id = ll_msg->gns_header.r_id;
865   llr_msg->private_key = ll_msg->zone;
866   llr_msg->name_len = htons (name_len);
867   llr_msg->rd_count = htons (rlc.res_rd_count);
868   llr_msg->rd_len = htons (rlc.rd_ser_len);
869   res_name = (char *) &llr_msg[1];
870   if  ((GNUNET_YES == rlc.found) && (GNUNET_OK == res))
871     llr_msg->found = ntohs (GNUNET_YES);
872   else
873     llr_msg->found = ntohs (GNUNET_NO);
874   memcpy (&llr_msg[1], name_tmp, name_len);
875   memcpy (&res_name[name_len], rlc.res_rd, rlc.rd_ser_len);
876
877   GNUNET_SERVER_notification_context_unicast (snc, client, &llr_msg->gns_header.header,
878       GNUNET_NO);
879
880   GNUNET_free_non_null (rlc.res_rd);
881   GNUNET_free (llr_msg);
882 }
883
884
885 /**
886  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE message
887  *
888  * @param cls unused
889  * @param client client sending the message
890  * @param message message of type 'struct RecordCreateMessage'
891  */
892 static void
893 handle_record_store (void *cls,
894                      struct GNUNET_SERVER_Client *client,
895                      const struct GNUNET_MessageHeader *message)
896 {
897   const struct RecordStoreMessage *rp_msg;
898   size_t name_len;
899   size_t msg_size;
900   size_t msg_size_exp;
901   size_t rd_ser_len;
902   uint32_t rid;
903   const char *name_tmp;
904   char *conv_name;
905   const char *rd_ser;
906   unsigned int rd_count;
907   int res;
908   struct GNUNET_CRYPTO_EcdsaPublicKey pubkey;
909   struct ZoneMonitor *zm;
910
911   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
912               "Received `%s' message\n",
913               "NAMESTORE_RECORD_STORE");
914   if (ntohs (message->size) < sizeof (struct RecordStoreMessage))
915   {
916     GNUNET_break (0);
917     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
918     return;
919   }
920   rp_msg = (const struct RecordStoreMessage *) message;
921   rid = ntohl (rp_msg->gns_header.r_id);
922   name_len = ntohs (rp_msg->name_len);
923   msg_size = ntohs (message->size);
924   rd_count = ntohs (rp_msg->rd_count);
925   rd_ser_len = ntohs (rp_msg->rd_len);
926   GNUNET_break (0 == ntohs (rp_msg->reserved));
927   msg_size_exp = sizeof (struct RecordStoreMessage) + name_len + rd_ser_len;
928   if (msg_size != msg_size_exp)
929   {
930     GNUNET_break (0);
931     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
932     return;
933   }
934   if ((0 == name_len) || (name_len > MAX_NAME_LEN))
935   {
936     GNUNET_break (0);
937     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
938     return;
939   }
940   name_tmp = (const char *) &rp_msg[1];
941   rd_ser = &name_tmp[name_len];
942   if ('\0' != name_tmp[name_len -1])
943   {
944     GNUNET_break (0);
945     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
946     return;
947   }
948   (void) client_lookup (client);
949   {
950     struct GNUNET_GNSRECORD_Data rd[rd_count];
951
952     if (GNUNET_OK !=
953         GNUNET_GNSRECORD_records_deserialize (rd_ser_len, rd_ser, rd_count, rd))
954     {
955       GNUNET_break (0);
956       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
957       return;
958     }
959
960     /* Extracting and converting private key */
961     GNUNET_CRYPTO_ecdsa_key_get_public (&rp_msg->private_key,
962                                       &pubkey);
963     conv_name = GNUNET_GNSRECORD_string_to_lowercase (name_tmp);
964     if (NULL == conv_name)
965     {
966       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
967                   "Error converting name `%s'\n", name_tmp);
968       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
969       return;
970     }
971     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
972                 "Creating %u records for name `%s' in zone `%s'\n",
973                 (unsigned int) rd_count,
974                 conv_name,
975                 GNUNET_GNSRECORD_z2s (&pubkey));
976
977     if ( (0 == rd_count) &&
978          (GNUNET_NO ==
979           GSN_database->iterate_records (GSN_database->cls,
980                                          &rp_msg->private_key, 0, NULL, 0)) )
981     {
982       /* This name does not exist, so cannot be removed */
983       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
984                   "Name `%s' does not exist, no deletion required\n",
985                   conv_name);
986       res = GNUNET_NO;
987     }
988     else
989     {
990       res = GSN_database->store_records (GSN_database->cls,
991                                          &rp_msg->private_key,
992                                          conv_name,
993                                          rd_count, rd);
994       if (GNUNET_OK == res)
995       {
996         for (zm = monitor_head; NULL != zm; zm = zm->next)
997         {
998           if ( (0 == memcmp (&rp_msg->private_key, &zm->zone,
999                              sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey))) ||
1000                (0 == memcmp (&zm->zone,
1001                              &zero,
1002                              sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey))) )
1003           {
1004             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1005                         "Notifying monitor about changes under label `%s'\n",
1006                         conv_name);
1007             send_lookup_response (monitor_nc,
1008                                   zm->nc->client,
1009                                   0,
1010                                   &rp_msg->private_key,
1011                                   conv_name,
1012                                   rd_count, rd);
1013           }
1014           else
1015             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1016                         "Monitor is for another zone\n");
1017         }
1018         if (NULL == monitor_head)
1019           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1020                       "No monitors active\n");
1021       }
1022       else
1023       {
1024         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1025                     "Error storing record: %d\n",
1026                     res);
1027       }
1028     }
1029     if (GNUNET_OK == res)
1030     {
1031       refresh_block (client, rid,
1032                      &rp_msg->private_key,
1033                      conv_name,
1034                      rd_count, rd);
1035       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1036       GNUNET_free (conv_name);
1037       return;
1038     }
1039     GNUNET_free (conv_name);
1040   }
1041   send_store_response (client, res, rid);
1042   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1043 }
1044
1045
1046 /**
1047  * Context for record remove operations passed from #handle_zone_to_name to
1048  * #handle_zone_to_name_it as closure
1049  */
1050 struct ZoneToNameCtx
1051 {
1052   /**
1053    * Namestore client
1054    */
1055   struct NamestoreClient *nc;
1056
1057   /**
1058    * Request id (to be used in the response to the client).
1059    */
1060   uint32_t rid;
1061
1062   /**
1063    * Set to #GNUNET_OK on success, #GNUNET_SYSERR on error.  Note that
1064    * not finding a name for the zone still counts as a 'success' here,
1065    * as this field is about the success of executing the IPC protocol.
1066    */
1067   int success;
1068 };
1069
1070
1071 /**
1072  * Zone to name iterator
1073  *
1074  * @param cls struct ZoneToNameCtx *
1075  * @param zone_key the zone key
1076  * @param name name
1077  * @param rd_count number of records in @a rd
1078  * @param rd record data
1079  */
1080 static void
1081 handle_zone_to_name_it (void *cls,
1082                         const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
1083                         const char *name,
1084                         unsigned int rd_count,
1085                         const struct GNUNET_GNSRECORD_Data *rd)
1086 {
1087   struct ZoneToNameCtx *ztn_ctx = cls;
1088   struct ZoneToNameResponseMessage *ztnr_msg;
1089   int16_t res;
1090   size_t name_len;
1091   size_t rd_ser_len;
1092   size_t msg_size;
1093   char *name_tmp;
1094   char *rd_tmp;
1095
1096   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1097               "Found result for zone-to-name lookup: `%s'\n",
1098               name);
1099   res = GNUNET_YES;
1100   name_len = (NULL == name) ? 0 : strlen (name) + 1;
1101   rd_ser_len = GNUNET_GNSRECORD_records_get_size (rd_count, rd);
1102   msg_size = sizeof (struct ZoneToNameResponseMessage) + name_len + rd_ser_len;
1103   if (msg_size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1104   {
1105     GNUNET_break (0);
1106     ztn_ctx->success = GNUNET_SYSERR;
1107     return;
1108   }
1109   ztnr_msg = GNUNET_malloc (msg_size);
1110   ztnr_msg->gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME_RESPONSE);
1111   ztnr_msg->gns_header.header.size = htons (msg_size);
1112   ztnr_msg->gns_header.r_id = htonl (ztn_ctx->rid);
1113   ztnr_msg->res = htons (res);
1114   ztnr_msg->rd_len = htons (rd_ser_len);
1115   ztnr_msg->rd_count = htons (rd_count);
1116   ztnr_msg->name_len = htons (name_len);
1117   ztnr_msg->zone = *zone_key;
1118   name_tmp = (char *) &ztnr_msg[1];
1119   if (NULL != name)
1120     memcpy (name_tmp, name, name_len);
1121   rd_tmp = &name_tmp[name_len];
1122   GNUNET_GNSRECORD_records_serialize (rd_count, rd, rd_ser_len, rd_tmp);
1123   ztn_ctx->success = GNUNET_OK;
1124   GNUNET_SERVER_notification_context_unicast (snc, ztn_ctx->nc->client,
1125                                               &ztnr_msg->gns_header.header,
1126                                               GNUNET_NO);
1127   GNUNET_free (ztnr_msg);
1128 }
1129
1130
1131 /**
1132  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME message
1133  *
1134  * @param cls unused
1135  * @param client client sending the message
1136  * @param message message of type 'struct ZoneToNameMessage'
1137  */
1138 static void
1139 handle_zone_to_name (void *cls,
1140                      struct GNUNET_SERVER_Client *client,
1141                      const struct GNUNET_MessageHeader *message)
1142 {
1143   struct NamestoreClient *nc;
1144   const struct ZoneToNameMessage *ztn_msg;
1145   struct ZoneToNameCtx ztn_ctx;
1146   struct ZoneToNameResponseMessage ztnr_msg;
1147
1148   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1149               "Received `%s' message\n",
1150               "ZONE_TO_NAME");
1151   ztn_msg = (const struct ZoneToNameMessage *) message;
1152   nc = client_lookup (client);
1153   ztn_ctx.rid = ntohl (ztn_msg->gns_header.r_id);
1154   ztn_ctx.nc = nc;
1155   ztn_ctx.success = GNUNET_NO;
1156   if (GNUNET_SYSERR ==
1157       GSN_database->zone_to_name (GSN_database->cls,
1158                                   &ztn_msg->zone,
1159                                   &ztn_msg->value_zone,
1160                                   &handle_zone_to_name_it, &ztn_ctx))
1161   {
1162     /* internal error, hang up instead of signalling something
1163        that might be wrong */
1164     GNUNET_break (0);
1165     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1166     return;
1167   }
1168   if (GNUNET_NO == ztn_ctx.success)
1169   {
1170     /* no result found, send empty response */
1171     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1172                 "Found no result for zone-to-name lookup.\n");
1173     memset (&ztnr_msg, 0, sizeof (ztnr_msg));
1174     ztnr_msg.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME_RESPONSE);
1175     ztnr_msg.gns_header.header.size = htons (sizeof (ztnr_msg));
1176     ztnr_msg.gns_header.r_id = ztn_msg->gns_header.r_id;
1177     ztnr_msg.res = htons (GNUNET_NO);
1178     GNUNET_SERVER_notification_context_unicast (snc,
1179                                                 client,
1180                                                 &ztnr_msg.gns_header.header,
1181                                                 GNUNET_NO);
1182   }
1183   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1184 }
1185
1186
1187 /**
1188  * Zone iteration processor result
1189  */
1190 enum ZoneIterationResult
1191 {
1192   /**
1193    * Iteration start.
1194    */
1195   IT_START = 0,
1196
1197   /**
1198    * Found records,
1199    * Continue to iterate with next iteration_next call
1200    */
1201   IT_SUCCESS_MORE_AVAILABLE = 1,
1202
1203   /**
1204    * Iteration complete
1205    */
1206   IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE = 2
1207 };
1208
1209
1210 /**
1211  * Context for record remove operations passed from
1212  * #run_zone_iteration_round to #zone_iterate_proc as closure
1213  */
1214 struct ZoneIterationProcResult
1215 {
1216   /**
1217    * The zone iteration handle
1218    */
1219   struct ZoneIteration *zi;
1220
1221   /**
1222    * Iteration result: iteration done?
1223    * #IT_SUCCESS_MORE_AVAILABLE:  if there may be more results overall but
1224    * we got one for now and have sent it to the client
1225    * #IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE: if there are no further results,
1226    * #IT_START: if we are still trying to find a result.
1227    */
1228   int res_iteration_finished;
1229
1230 };
1231
1232
1233 /**
1234  * Process results for zone iteration from database
1235  *
1236  * @param cls struct ZoneIterationProcResult *proc
1237  * @param zone_key the zone key
1238  * @param name name
1239  * @param rd_count number of records for this name
1240  * @param rd record data
1241  */
1242 static void
1243 zone_iterate_proc (void *cls,
1244                        const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
1245                        const char *name,
1246                        unsigned int rd_count,
1247                        const struct GNUNET_GNSRECORD_Data *rd)
1248 {
1249   struct ZoneIterationProcResult *proc = cls;
1250   unsigned int i;
1251   int do_refresh_block;
1252
1253   if ((NULL == zone_key) && (NULL == name))
1254   {
1255     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1256                 "Iteration done\n");
1257     proc->res_iteration_finished = IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE;
1258     return;
1259   }
1260   if ((NULL == zone_key) || (NULL == name))
1261   {
1262     /* what is this!? should never happen */
1263     proc->res_iteration_finished = IT_START;
1264     GNUNET_break (0);
1265     return;
1266   }
1267   proc->res_iteration_finished = IT_SUCCESS_MORE_AVAILABLE;
1268   send_lookup_response (snc,
1269                         proc->zi->client->client,
1270                         proc->zi->request_id,
1271                         zone_key,
1272                         name,
1273                         rd_count,
1274                         rd);
1275   do_refresh_block = GNUNET_NO;
1276   for (i=0;i<rd_count;i++)
1277     if(  (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION)) &&
1278          (0 == (rd[i].flags & GNUNET_GNSRECORD_RF_PENDING)) )
1279     {
1280       do_refresh_block = GNUNET_YES;
1281       break;
1282     }
1283   if (GNUNET_YES == do_refresh_block)
1284     refresh_block (NULL, 0,
1285                    zone_key,
1286                    name,
1287                    rd_count,
1288                    rd);
1289
1290 }
1291
1292
1293 /**
1294  * Perform the next round of the zone iteration.
1295  *
1296  * @param zi zone iterator to process
1297  */
1298 static void
1299 run_zone_iteration_round (struct ZoneIteration *zi)
1300 {
1301   struct ZoneIterationProcResult proc;
1302   struct RecordResultMessage rrm;
1303   int ret;
1304
1305   memset (&proc, 0, sizeof (proc));
1306   proc.zi = zi;
1307   proc.res_iteration_finished = IT_START;
1308   while (IT_START == proc.res_iteration_finished)
1309   {
1310     if (GNUNET_SYSERR ==
1311         (ret = GSN_database->iterate_records (GSN_database->cls,
1312                                               (0 == memcmp (&zi->zone, &zero, sizeof (zero)))
1313                                               ? NULL
1314                                               : &zi->zone,
1315                                               zi->offset,
1316                                               &zone_iterate_proc, &proc)))
1317     {
1318       GNUNET_break (0);
1319       break;
1320     }
1321     if (GNUNET_NO == ret)
1322       proc.res_iteration_finished = IT_SUCCESS_NOT_MORE_RESULTS_AVAILABLE;
1323     zi->offset++;
1324   }
1325   if (IT_SUCCESS_MORE_AVAILABLE == proc.res_iteration_finished)
1326   {
1327     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1328                 "More results available\n");
1329     return; /* more results later */
1330   }
1331   /* send empty response to indicate end of list */
1332   memset (&rrm, 0, sizeof (rrm));
1333   rrm.gns_header.header.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT);
1334   rrm.gns_header.header.size = htons (sizeof (rrm));
1335   rrm.gns_header.r_id = htonl (zi->request_id);
1336   GNUNET_SERVER_notification_context_unicast (snc,
1337                                               zi->client->client,
1338                                               &rrm.gns_header.header,
1339                                               GNUNET_NO);
1340   GNUNET_CONTAINER_DLL_remove (zi->client->op_head,
1341                                zi->client->op_tail,
1342                                zi);
1343   GNUNET_free (zi);
1344 }
1345
1346
1347 /**
1348  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_START message
1349  *
1350  * @param cls unused
1351  * @param client the client sending the message
1352  * @param message message of type 'struct ZoneIterationStartMessage'
1353  */
1354 static void
1355 handle_iteration_start (void *cls,
1356                         struct GNUNET_SERVER_Client *client,
1357                         const struct GNUNET_MessageHeader *message)
1358 {
1359   const struct ZoneIterationStartMessage *zis_msg;
1360   struct NamestoreClient *nc;
1361   struct ZoneIteration *zi;
1362
1363   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message\n", "ZONE_ITERATION_START");
1364   if (NULL == (nc = client_lookup (client)))
1365   {
1366     GNUNET_break (0);
1367     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1368     return;
1369   }
1370   zis_msg = (const struct ZoneIterationStartMessage *) message;
1371   zi = GNUNET_new (struct ZoneIteration);
1372   zi->request_id = ntohl (zis_msg->gns_header.r_id);
1373   zi->offset = 0;
1374   zi->client = nc;
1375   zi->zone = zis_msg->zone;
1376
1377
1378   GNUNET_CONTAINER_DLL_insert (nc->op_head, nc->op_tail, zi);
1379   run_zone_iteration_round (zi);
1380   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1381 }
1382
1383
1384 /**
1385  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_STOP message
1386  *
1387  * @param cls unused
1388  * @param client GNUNET_SERVER_Client sending the message
1389  * @param message message of type 'struct ZoneIterationStopMessage'
1390  */
1391 static void
1392 handle_iteration_stop (void *cls,
1393                        struct GNUNET_SERVER_Client *client,
1394                        const struct GNUNET_MessageHeader *message)
1395 {
1396   struct NamestoreClient *nc;
1397   struct ZoneIteration *zi;
1398   const struct ZoneIterationStopMessage *zis_msg;
1399   uint32_t rid;
1400
1401   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1402               "Received `%s' message\n",
1403               "ZONE_ITERATION_STOP");
1404   if (NULL == (nc = client_lookup(client)))
1405   {
1406     GNUNET_break (0);
1407     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1408     return;
1409   }
1410   zis_msg = (const struct ZoneIterationStopMessage *) message;
1411   rid = ntohl (zis_msg->gns_header.r_id);
1412   for (zi = nc->op_head; NULL != zi; zi = zi->next)
1413     if (zi->request_id == rid)
1414       break;
1415   if (NULL == zi)
1416   {
1417     GNUNET_break (0);
1418     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1419     return;
1420   }
1421   GNUNET_CONTAINER_DLL_remove (nc->op_head, nc->op_tail, zi);
1422   GNUNET_free (zi);
1423   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1424 }
1425
1426
1427 /**
1428  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_NEXT message
1429  *
1430  * @param cls unused
1431  * @param client GNUNET_SERVER_Client sending the message
1432  * @param message message of type 'struct ZoneIterationNextMessage'
1433  */
1434 static void
1435 handle_iteration_next (void *cls,
1436                        struct GNUNET_SERVER_Client *client,
1437                        const struct GNUNET_MessageHeader *message)
1438 {
1439   struct NamestoreClient *nc;
1440   struct ZoneIteration *zi;
1441   const struct ZoneIterationNextMessage *zis_msg;
1442   uint32_t rid;
1443
1444   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1445               "Received `%s' message\n",
1446               "ZONE_ITERATION_NEXT");
1447   if (NULL == (nc = client_lookup(client)))
1448   {
1449     GNUNET_break (0);
1450     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1451     return;
1452   }
1453   zis_msg = (const struct ZoneIterationNextMessage *) message;
1454   rid = ntohl (zis_msg->gns_header.r_id);
1455   for (zi = nc->op_head; NULL != zi; zi = zi->next)
1456     if (zi->request_id == rid)
1457       break;
1458   if (NULL == zi)
1459   {
1460     GNUNET_break (0);
1461     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1462     return;
1463   }
1464   run_zone_iteration_round (zi);
1465   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1466 }
1467
1468
1469 /**
1470  * Send 'sync' message to zone monitor, we're now in sync.
1471  *
1472  * @param zm monitor that is now in sync
1473  */
1474 static void
1475 monitor_sync (struct ZoneMonitor *zm)
1476 {
1477   struct GNUNET_MessageHeader sync;
1478
1479   sync.size = htons (sizeof (struct GNUNET_MessageHeader));
1480   sync.type = htons (GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_SYNC);
1481   GNUNET_SERVER_notification_context_unicast (monitor_nc,
1482                                               zm->nc->client,
1483                                               &sync,
1484                                               GNUNET_NO);
1485 }
1486
1487
1488 /**
1489  * Obtain the next datum during the zone monitor's zone intiial iteration.
1490  *
1491  * @param cls zone monitor that does its initial iteration
1492  * @param tc scheduler context
1493  */
1494 static void
1495 monitor_next (void *cls,
1496               const struct GNUNET_SCHEDULER_TaskContext *tc);
1497
1498
1499 /**
1500  * A #GNUNET_NAMESTORE_RecordIterator for monitors.
1501  *
1502  * @param cls a 'struct ZoneMonitor *' with information about the monitor
1503  * @param zone_key zone key of the zone
1504  * @param name name
1505  * @param rd_count number of records in @a rd
1506  * @param rd array of records
1507  */
1508 static void
1509 monitor_iterate_cb (void *cls,
1510                     const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key,
1511                     const char *name,
1512                     unsigned int rd_count,
1513                     const struct GNUNET_GNSRECORD_Data *rd)
1514 {
1515   struct ZoneMonitor *zm = cls;
1516
1517   if (NULL == name)
1518   {
1519     /* finished with iteration */
1520     monitor_sync (zm);
1521     return;
1522   }
1523   send_lookup_response (monitor_nc,
1524                         zm->nc->client,
1525                         0,
1526                         zone_key,
1527                         name,
1528                         rd_count,
1529                         rd);
1530   zm->task = GNUNET_SCHEDULER_add_now (&monitor_next, zm);
1531 }
1532
1533
1534 /**
1535  * Handles a #GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_START message
1536  *
1537  * @param cls unused
1538  * @param client the client sending the message
1539  * @param message message of type 'struct ZoneMonitorStartMessage'
1540  */
1541 static void
1542 handle_monitor_start (void *cls,
1543                       struct GNUNET_SERVER_Client *client,
1544                       const struct GNUNET_MessageHeader *message)
1545 {
1546   const struct ZoneMonitorStartMessage *zis_msg;
1547   struct ZoneMonitor *zm;
1548
1549   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1550               "Received `%s' message\n",
1551               "ZONE_MONITOR_START");
1552   zis_msg = (const struct ZoneMonitorStartMessage *) message;
1553   zm = GNUNET_new (struct ZoneMonitor);
1554   zm->offset = 0;
1555   zm->nc = client_lookup (client);
1556   zm->zone = zis_msg->zone;
1557   GNUNET_CONTAINER_DLL_insert (monitor_head, monitor_tail, zm);
1558   GNUNET_SERVER_client_mark_monitor (client);
1559   GNUNET_SERVER_disable_receive_done_warning (client);
1560   GNUNET_SERVER_notification_context_add (monitor_nc,
1561                                           client);
1562   if (GNUNET_YES == ntohl (zis_msg->iterate_first))
1563     zm->task = GNUNET_SCHEDULER_add_now (&monitor_next, zm);
1564   else
1565     monitor_sync (zm);
1566 }
1567
1568
1569 /**
1570  * Obtain the next datum during the zone monitor's zone intiial iteration.
1571  *
1572  * @param cls zone monitor that does its initial iteration
1573  * @param tc scheduler context
1574  */
1575 static void
1576 monitor_next (void *cls,
1577               const struct GNUNET_SCHEDULER_TaskContext *tc)
1578 {
1579   struct ZoneMonitor *zm = cls;
1580   int ret;
1581
1582   zm->task = GNUNET_SCHEDULER_NO_TASK;
1583   ret = GSN_database->iterate_records (GSN_database->cls,
1584                                        (0 == memcmp (&zm->zone, &zero, sizeof (zero)))
1585                                        ? NULL
1586                                        : &zm->zone,
1587                                        zm->offset++,
1588                                        &monitor_iterate_cb, zm);
1589   if (GNUNET_SYSERR == ret)
1590   {
1591     GNUNET_SERVER_client_disconnect (zm->nc->client);
1592     return;
1593   }
1594   if (GNUNET_NO == ret)
1595   {
1596     /* empty zone */
1597     monitor_sync (zm);
1598     return;
1599   }
1600 }
1601
1602
1603 /**
1604  * Process namestore requests.
1605  *
1606  * @param cls closure
1607  * @param server the initialized server
1608  * @param cfg configuration to use
1609  */
1610 static void
1611 run (void *cls, struct GNUNET_SERVER_Handle *server,
1612      const struct GNUNET_CONFIGURATION_Handle *cfg)
1613 {
1614   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1615     {&handle_record_store, NULL,
1616      GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE, 0},
1617     {&handle_record_lookup, NULL,
1618      GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_LOOKUP, 0},
1619     {&handle_zone_to_name, NULL,
1620      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME, sizeof (struct ZoneToNameMessage) },
1621     {&handle_iteration_start, NULL,
1622      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_START, sizeof (struct ZoneIterationStartMessage) },
1623     {&handle_iteration_next, NULL,
1624      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_NEXT, sizeof (struct ZoneIterationNextMessage) },
1625     {&handle_iteration_stop, NULL,
1626      GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_STOP, sizeof (struct ZoneIterationStopMessage) },
1627     {&handle_monitor_start, NULL,
1628      GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_START, sizeof (struct ZoneMonitorStartMessage) },
1629     {NULL, NULL, 0, 0}
1630   };
1631   char *database;
1632
1633   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting namestore service\n");
1634   GSN_cfg = cfg;
1635   monitor_nc = GNUNET_SERVER_notification_context_create (server, 1);
1636   namecache = GNUNET_NAMECACHE_connect (cfg);
1637   /* Loading database plugin */
1638   if (GNUNET_OK !=
1639       GNUNET_CONFIGURATION_get_value_string (cfg, "namestore", "database",
1640                                              &database))
1641     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No database backend configured\n");
1642
1643   GNUNET_asprintf (&db_lib_name, "libgnunet_plugin_namestore_%s", database);
1644   GSN_database = GNUNET_PLUGIN_load (db_lib_name, (void *) GSN_cfg);
1645   GNUNET_free (database);
1646   if (NULL == GSN_database)
1647   {
1648     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1649                 "Could not load database backend `%s'\n",
1650                 db_lib_name);
1651     GNUNET_SCHEDULER_add_now (&cleanup_task, NULL);
1652     return;
1653   }
1654
1655   /* Configuring server handles */
1656   GNUNET_SERVER_add_handlers (server, handlers);
1657   snc = GNUNET_SERVER_notification_context_create (server, 16);
1658   GNUNET_SERVER_disconnect_notify (server,
1659                                    &client_disconnect_notification,
1660                                    NULL);
1661   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleanup_task,
1662                                 NULL);
1663 }
1664
1665
1666 /**
1667  * The main function for the template service.
1668  *
1669  * @param argc number of arguments from the command line
1670  * @param argv command line arguments
1671  * @return 0 ok, 1 on error
1672  */
1673 int
1674 main (int argc, char *const *argv)
1675 {
1676   return (GNUNET_OK ==
1677           GNUNET_SERVICE_run (argc, argv, "namestore",
1678                               GNUNET_SERVICE_OPTION_NONE, &run, NULL)) ? 0 : 1;
1679 }
1680
1681 /* end of gnunet-service-namestore.c */
1682