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