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