386e6d7449e7e3cddeebf84e4f5df1e00809f36e
[oweals/gnunet.git] / src / gns / gnunet-service-gns.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2011-2013 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  * @file gns/gnunet-service-gns.c
22  * @brief GNU Name System (main service)
23  * @author Martin Schanzenbach
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_dns_service.h"
29 #include "gnunet_dnsparser_lib.h"
30 #include "gnunet_dht_service.h"
31 #include "gnunet_namecache_service.h"
32 #include "gnunet_namestore_service.h"
33 #include "gnunet_identity_service.h"
34 #include "gnunet_gns_service.h"
35 #include "gnunet_statistics_service.h"
36 #include "gns.h"
37 #include "gnunet-service-gns_resolver.h"
38 #include "gnunet-service-gns_shorten.h"
39 #include "gnunet-service-gns_interceptor.h"
40 #include "gnunet_protocols.h"
41
42 /**
43  * The initial interval in milliseconds btween puts in
44  * a zone iteration
45  */
46 #define INITIAL_PUT_INTERVAL GNUNET_TIME_UNIT_MILLISECONDS
47
48 /**
49  * The lower bound for the zone iteration interval
50  */
51 #define MINIMUM_ZONE_ITERATION_INTERVAL GNUNET_TIME_UNIT_SECONDS
52
53 /**
54  * The upper bound for the zone iteration interval
55  */
56 #define MAXIMUM_ZONE_ITERATION_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
57
58 /**
59  * The default put interval for the zone iteration. In case
60  * no option is found
61  */
62 #define DEFAULT_ZONE_PUBLISH_TIME_WINDOW GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 4)
63
64 /**
65  * The factor the current zone iteration interval is divided by for each
66  * additional new record
67  */
68 #define LATE_ITERATION_SPEEDUP_FACTOR 2
69
70 /**
71  * How long until a DHT PUT attempt should time out?
72  */
73 #define DHT_OPERATION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
74
75 /**
76  * What replication level do we use for DHT PUT operations?
77  */
78 #define DHT_GNS_REPLICATION_LEVEL 5
79
80 /**
81  * GnsClient prototype
82  */
83 struct GnsClient;
84
85 /**
86  * Handle to a lookup operation from api
87  */
88 struct ClientLookupHandle
89 {
90
91   /**
92    * We keep these in a DLL.
93    */
94   struct ClientLookupHandle *next;
95
96   /**
97    * We keep these in a DLL.
98    */
99   struct ClientLookupHandle *prev;
100   
101   /**
102    * Client handle
103    */
104   struct GnsClient *gc;
105
106   /**
107    * Active handle for the lookup.
108    */
109   struct GNS_ResolverHandle *lookup;
110
111   /**
112    * request id
113    */
114   uint32_t request_id;
115
116 };
117
118 struct GnsClient
119 {
120   /**
121    * The client
122    */
123   struct GNUNET_SERVICE_Client *client;
124
125   /**
126    * The MQ
127    */
128   struct GNUNET_MQ_Handle *mq;
129
130   /**
131    * Head of the DLL.
132    */
133   struct ClientLookupHandle *clh_head;
134
135   /**
136    * Tail of the DLL.
137    */
138   struct ClientLookupHandle *clh_tail;
139 };
140
141
142 /**
143  * Handle for DHT PUT activity triggered from the namestore monitor.
144  */
145 struct MonitorActivity
146 {
147   /**
148    * Kept in a DLL.
149    */
150   struct MonitorActivity *next;
151
152   /**
153    * Kept in a DLL.
154    */
155   struct MonitorActivity *prev;
156
157   /**
158    * Handle for the DHT PUT operation.
159    */
160   struct GNUNET_DHT_PutHandle *ph;
161 };
162
163
164 /**
165  * Our handle to the DHT
166  */
167 static struct GNUNET_DHT_Handle *dht_handle;
168
169 /**
170  * Active DHT put operation (or NULL)
171  */
172 static struct GNUNET_DHT_PutHandle *active_put;
173
174 /**
175  * Our handle to the namestore service
176  */
177 static struct GNUNET_NAMESTORE_Handle *namestore_handle;
178
179 /**
180  * Our handle to the namecache service
181  */
182 static struct GNUNET_NAMECACHE_Handle *namecache_handle;
183
184 /**
185  * Our handle to the identity service
186  */
187 static struct GNUNET_IDENTITY_Handle *identity_handle;
188
189 /**
190  * Our handle to the identity operation to find the master zone
191  * for intercepted queries.
192  */
193 static struct GNUNET_IDENTITY_Operation *identity_op;
194
195 /**
196  * Handle to iterate over our authoritative zone in namestore
197  */
198 static struct GNUNET_NAMESTORE_ZoneIterator *namestore_iter;
199
200 /**
201  * Handle to monitor namestore changes to instant propagation.
202  */
203 static struct GNUNET_NAMESTORE_ZoneMonitor *zmon;
204
205 /**
206  * Head of monitor activities; kept in a DLL.
207  */
208 static struct MonitorActivity *ma_head;
209
210 /**
211  * Tail of monitor activities; kept in a DLL.
212  */
213 static struct MonitorActivity *ma_tail;
214
215 /**
216  * Useful for zone update for DHT put
217  */
218 static unsigned long long num_public_records;
219
220 /**
221  * Last seen record count
222  */
223 static unsigned long long last_num_public_records;
224
225 /**
226  * Minimum relative expiration time of records seem during the current
227  * zone iteration.
228  */
229 static struct GNUNET_TIME_Relative min_relative_record_time;
230
231 /**
232  * Zone iteration PUT interval.
233  */
234 static struct GNUNET_TIME_Relative put_interval;
235
236 /**
237  * Default time window for zone iteration
238  */
239 static struct GNUNET_TIME_Relative zone_publish_time_window_default;
240
241 /**
242  * Time window for zone iteration, adjusted based on relative record
243  * expiration times in our zone.
244  */
245 static struct GNUNET_TIME_Relative zone_publish_time_window;
246
247 /**
248  * zone publish task
249  */
250 static struct GNUNET_SCHEDULER_Task *zone_publish_task;
251
252 /**
253  * #GNUNET_YES if zone has never been published before
254  */
255 static int first_zone_iteration;
256
257 /**
258  * #GNUNET_YES if ipv6 is supported
259  */
260 static int v6_enabled;
261
262 /**
263  * #GNUNET_YES if ipv4 is supported
264  */
265 static int v4_enabled;
266
267 /**
268  * Handle to the statistics service
269  */
270 static struct GNUNET_STATISTICS_Handle *statistics;
271
272
273 /**
274  * Task run during shutdown.
275  *
276  * @param cls unused
277  * @param tc unused
278  */
279 static void
280 shutdown_task (void *cls)
281 {
282   struct MonitorActivity *ma;
283
284   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
285               "Shutting down!\n");
286   GNS_interceptor_done ();
287   if (NULL != identity_op)
288   {
289     GNUNET_IDENTITY_cancel (identity_op);
290     identity_op = NULL;
291   }
292   if (NULL != identity_handle)
293   {
294     GNUNET_IDENTITY_disconnect (identity_handle);
295     identity_handle = NULL;
296   }
297   GNS_resolver_done ();
298   GNS_shorten_done ();
299   while (NULL != (ma = ma_head))
300   {
301     GNUNET_DHT_put_cancel (ma->ph);
302     GNUNET_CONTAINER_DLL_remove (ma_head,
303                                  ma_tail,
304                                  ma);
305     GNUNET_free (ma);
306   }
307   if (NULL != statistics)
308   {
309     GNUNET_STATISTICS_destroy (statistics,
310                                GNUNET_NO);
311     statistics = NULL;
312   }
313   if (NULL != zone_publish_task)
314   {
315     GNUNET_SCHEDULER_cancel (zone_publish_task);
316     zone_publish_task = NULL;
317   }
318   if (NULL != namestore_iter)
319   {
320     GNUNET_NAMESTORE_zone_iteration_stop (namestore_iter);
321     namestore_iter = NULL;
322   }
323   if (NULL != zmon)
324   {
325     GNUNET_NAMESTORE_zone_monitor_stop (zmon);
326     zmon = NULL;
327   }
328   if (NULL != namestore_handle)
329   {
330     GNUNET_NAMESTORE_disconnect (namestore_handle);
331     namestore_handle = NULL;
332   }
333   if (NULL != namecache_handle)
334   {
335     GNUNET_NAMECACHE_disconnect (namecache_handle);
336     namecache_handle = NULL;
337   }
338   if (NULL != active_put)
339   {
340     GNUNET_DHT_put_cancel (active_put);
341     active_put = NULL;
342   }
343   if (NULL != dht_handle)
344   {
345     GNUNET_DHT_disconnect (dht_handle);
346     dht_handle = NULL;
347   }
348 }
349
350 /**
351  * Called whenever a client is disconnected.
352  *
353  * @param cls closure
354  * @param client identification of the client
355  * @param app_ctx @a client
356  */
357 static void
358 client_disconnect_cb (void *cls,
359                       struct GNUNET_SERVICE_Client *client,
360                       void *app_ctx)
361 {
362   struct ClientLookupHandle *clh;
363   struct GnsClient *gc = app_ctx;
364
365   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
366               "Client %p disconnected\n",
367               client);
368   while (NULL != (clh = gc->clh_head))
369   {
370     GNS_resolver_lookup_cancel (clh->lookup);
371     GNUNET_CONTAINER_DLL_remove (gc->clh_head,
372                                  gc->clh_tail,
373                                  clh);
374     GNUNET_free (clh);
375   }
376
377   GNUNET_free (gc); 
378 }
379
380
381 /**
382  * Add a client to our list of active clients.
383  *
384  * @param cls NULL
385  * @param client client to add
386  * @param mq message queue for @a client
387  * @return internal namestore client structure for this client
388  */
389 static void *
390 client_connect_cb (void *cls,
391                    struct GNUNET_SERVICE_Client *client,
392                    struct GNUNET_MQ_Handle *mq)
393 {
394   struct GnsClient *gc;
395   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
396               "Client %p connected\n",
397               client);
398   gc = GNUNET_new (struct GnsClient);
399   gc->client = client;
400   gc->mq = mq;
401   return gc;
402 }
403
404
405 /**
406  * Method called periodically that triggers iteration over authoritative records
407  *
408  * @param cls closure
409  */
410 static void
411 publish_zone_dht_next (void *cls)
412 {
413   zone_publish_task = NULL;
414   GNUNET_assert (NULL != namestore_iter);
415   GNUNET_NAMESTORE_zone_iterator_next (namestore_iter);
416 }
417
418
419 /**
420  * Periodically iterate over our zone and store everything in dht
421  *
422  * @param cls NULL
423  */
424 static void
425 publish_zone_dht_start (void *cls);
426
427
428 /**
429  * Continuation called from DHT once the PUT operation is done.
430  *
431  * @param cls closure, NULL if called from regular iteration,
432  *        `struct MonitorActivity` if called from #handle_monitor_event.
433  * @param success #GNUNET_OK on success
434  */
435 static void
436 dht_put_continuation (void *cls,
437                       int success)
438 {
439   struct MonitorActivity *ma = cls;
440   struct GNUNET_TIME_Relative next_put_interval;
441
442   num_public_records++;
443   if (NULL == ma)
444   {
445     active_put = NULL;
446     if ( (num_public_records > last_num_public_records) &&
447          (GNUNET_NO == first_zone_iteration) )
448     {
449       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
450                   "Last record count was lower than current record count.  Reducing interval.\n");
451       put_interval = GNUNET_TIME_relative_divide (zone_publish_time_window,
452                                                   num_public_records);
453       next_put_interval = GNUNET_TIME_relative_divide (put_interval,
454                                                        LATE_ITERATION_SPEEDUP_FACTOR);
455     }
456     else
457       next_put_interval = put_interval;
458     next_put_interval = GNUNET_TIME_relative_min (next_put_interval,
459                                                   MAXIMUM_ZONE_ITERATION_INTERVAL);
460     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
461                 "PUT complete, next PUT in %s!\n",
462                 GNUNET_STRINGS_relative_time_to_string (next_put_interval,
463                                                         GNUNET_YES));
464
465     GNUNET_STATISTICS_set (statistics,
466                            "Current zone iteration interval (ms)",
467                            next_put_interval.rel_value_us / 1000LL,
468                            GNUNET_NO);
469     GNUNET_assert (NULL == zone_publish_task);
470     zone_publish_task = GNUNET_SCHEDULER_add_delayed (next_put_interval,
471                                                       &publish_zone_dht_next,
472                                                       NULL);
473   }
474   else
475   {
476     GNUNET_CONTAINER_DLL_remove (ma_head,
477                                  ma_tail,
478                                  ma);
479     GNUNET_free (ma);
480   }
481 }
482
483
484 /**
485  * Convert namestore records from the internal format to that
486  * suitable for publication (removes private records, converts
487  * to absolute expiration time).
488  *
489  * @param rd input records
490  * @param rd_count size of the @a rd and @a rd_public arrays
491  * @param rd_public where to write the converted records
492  * @return number of records written to @a rd_public
493  */
494 static unsigned int
495 convert_records_for_export (const struct GNUNET_GNSRECORD_Data *rd,
496                             unsigned int rd_count,
497                             struct GNUNET_GNSRECORD_Data *rd_public)
498 {
499   struct GNUNET_TIME_Absolute now;
500   unsigned int rd_public_count;
501   unsigned int i;
502
503   rd_public_count = 0;
504   now = GNUNET_TIME_absolute_get ();
505   for (i=0;i<rd_count;i++)
506     if (0 == (rd[i].flags & GNUNET_GNSRECORD_RF_PRIVATE))
507     {
508       rd_public[rd_public_count] = rd[i];
509       if (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION))
510       {
511         /* GNUNET_GNSRECORD_block_create will convert to absolute time;
512            we just need to adjust our iteration frequency */
513         min_relative_record_time.rel_value_us =
514           GNUNET_MIN (rd_public[rd_public_count].expiration_time,
515                       min_relative_record_time.rel_value_us);
516       }
517       else if (rd_public[rd_public_count].expiration_time < now.abs_value_us)
518       {
519         /* record already expired, skip it */
520         continue;
521       }
522       rd_public_count++;
523     }
524   return rd_public_count;
525 }
526
527
528 /**
529  * Store GNS records in the DHT.
530  *
531  * @param key key of the zone
532  * @param label label to store under
533  * @param rd_public public record data
534  * @param rd_public_count number of records in @a rd_public
535  * @param pc_arg closure argument to pass to the #dht_put_continuation
536  * @return DHT PUT handle, NULL on error
537  */
538 static struct GNUNET_DHT_PutHandle *
539 perform_dht_put (const struct GNUNET_CRYPTO_EcdsaPrivateKey *key,
540                  const char *label,
541                  const struct GNUNET_GNSRECORD_Data *rd_public,
542                  unsigned int rd_public_count,
543                  void *pc_arg)
544 {
545   struct GNUNET_GNSRECORD_Block *block;
546   struct GNUNET_HashCode query;
547   struct GNUNET_TIME_Absolute expire;
548   size_t block_size;
549   struct GNUNET_DHT_PutHandle *ret;
550
551   expire = GNUNET_GNSRECORD_record_get_expiration_time (rd_public_count,
552                                                         rd_public);
553   block = GNUNET_GNSRECORD_block_create (key,
554                                          expire,
555                                          label,
556                                          rd_public,
557                                          rd_public_count);
558   if (NULL == block)
559     return NULL; /* whoops */
560   block_size = ntohl (block->purpose.size)
561     + sizeof (struct GNUNET_CRYPTO_EcdsaSignature)
562     + sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey);
563   GNUNET_GNSRECORD_query_from_private_key (key,
564                                            label,
565                                            &query);
566   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
567               "Storing %u record(s) for label `%s' in DHT with expiration `%s' under key %s\n",
568               rd_public_count,
569               label,
570               GNUNET_STRINGS_absolute_time_to_string (expire),
571               GNUNET_h2s (&query));
572   ret = GNUNET_DHT_put (dht_handle,
573                         &query,
574                         DHT_GNS_REPLICATION_LEVEL,
575                         GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
576                         GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
577                         block_size,
578                         block,
579                         expire,
580                         &dht_put_continuation,
581                         pc_arg);
582   GNUNET_free (block);
583   return ret;
584 }
585
586
587 /**
588  * We encountered an error in our zone iteration.
589  */
590 static void
591 zone_iteration_error (void *cls)
592 {
593   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
594               "Got disconnected from namestore database, retrying.\n");
595   namestore_iter = NULL;
596   /* We end up here on error/disconnect/shutdown, so potentially
597      while a zone publish task or a DHT put is still running; hence
598      we need to cancel those. */
599   if (NULL != zone_publish_task)
600   {
601     GNUNET_SCHEDULER_cancel (zone_publish_task);
602     zone_publish_task = NULL;
603   }
604   if (NULL != active_put)
605   {
606     GNUNET_DHT_put_cancel (active_put);
607     active_put = NULL;
608   }
609   zone_publish_task = GNUNET_SCHEDULER_add_now (&publish_zone_dht_start,
610                                                 NULL);
611 }
612
613
614 /**
615  * Zone iteration is completed.
616  */
617 static void
618 zone_iteration_finished (void *cls)
619 {
620   /* we're done with one iteration, calculate when to do the next one */
621   namestore_iter = NULL;
622   last_num_public_records = num_public_records;
623   first_zone_iteration = GNUNET_NO;
624   if (0 == num_public_records)
625   {
626     /**
627      * If no records are known (startup) or none present
628      * we can safely set the interval to the value for a single
629      * record
630      */
631     put_interval = zone_publish_time_window;
632     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
633                 "No records in namestore database.\n");
634   }
635   else
636   {
637     /* If records are present, next publication is based on the minimum
638      * relative expiration time of the records published divided by 4
639      */
640     zone_publish_time_window
641       = GNUNET_TIME_relative_min (GNUNET_TIME_relative_divide (min_relative_record_time, 4),
642                                   zone_publish_time_window_default);
643     put_interval = GNUNET_TIME_relative_divide (zone_publish_time_window,
644                                                 num_public_records);
645   }
646   /* reset for next iteration */
647   min_relative_record_time = GNUNET_TIME_UNIT_FOREVER_REL;
648   put_interval = GNUNET_TIME_relative_max (MINIMUM_ZONE_ITERATION_INTERVAL,
649                                            put_interval);
650   put_interval = GNUNET_TIME_relative_min (put_interval,
651                                            MAXIMUM_ZONE_ITERATION_INTERVAL);
652   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
653               "Zone iteration finished. Adjusted zone iteration interval to %s\n",
654               GNUNET_STRINGS_relative_time_to_string (put_interval,
655                                                       GNUNET_YES));
656   GNUNET_STATISTICS_set (statistics,
657                          "Current zone iteration interval (in ms)",
658                          put_interval.rel_value_us / 1000LL,
659                          GNUNET_NO);
660   GNUNET_STATISTICS_update (statistics,
661                             "Number of zone iterations",
662                             1,
663                             GNUNET_NO);
664   GNUNET_STATISTICS_set (statistics,
665                          "Number of public records in DHT",
666                          last_num_public_records,
667                          GNUNET_NO);
668   GNUNET_assert (NULL == zone_publish_task);
669   if (0 == num_public_records)
670     zone_publish_task = GNUNET_SCHEDULER_add_delayed (put_interval,
671                                                       &publish_zone_dht_start,
672                                                       NULL);
673   else
674     zone_publish_task = GNUNET_SCHEDULER_add_now (&publish_zone_dht_start,
675                                                   NULL);
676 }
677
678
679 /**
680  * Function used to put all records successively into the DHT.
681  *
682  * @param cls the closure (NULL)
683  * @param key the private key of the authority (ours)
684  * @param label the name of the records, NULL once the iteration is done
685  * @param rd_count the number of records in @a rd
686  * @param rd the record data
687  */
688 static void
689 put_gns_record (void *cls,
690                 const struct GNUNET_CRYPTO_EcdsaPrivateKey *key,
691                 const char *label,
692                 unsigned int rd_count,
693                 const struct GNUNET_GNSRECORD_Data *rd)
694 {
695   struct GNUNET_GNSRECORD_Data rd_public[rd_count];
696   unsigned int rd_public_count;
697
698   rd_public_count = convert_records_for_export (rd,
699                                                 rd_count,
700                                                 rd_public);
701
702   if (0 == rd_public_count)
703   {
704     GNUNET_assert (NULL == zone_publish_task);
705     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
706                 "Record set empty, moving to next record set\n");
707     zone_publish_task = GNUNET_SCHEDULER_add_now (&publish_zone_dht_next,
708                                                   NULL);
709     return;
710   }
711   /* We got a set of records to publish */
712   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
713               "Starting DHT PUT\n");
714   active_put = perform_dht_put (key,
715                                 label,
716                                 rd_public,
717                                 rd_public_count,
718                                 NULL);
719   if (NULL == active_put)
720   {
721     GNUNET_break (0);
722     dht_put_continuation (NULL, GNUNET_NO);
723   }
724 }
725
726
727 /**
728  * Periodically iterate over all zones and store everything in DHT
729  *
730  * @param cls NULL
731  */
732 static void
733 publish_zone_dht_start (void *cls)
734 {
735   zone_publish_task = NULL;
736
737   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
738               "Starting DHT zone update!\n");
739   /* start counting again */
740   num_public_records = 0;
741   GNUNET_assert (NULL == namestore_iter);
742   namestore_iter
743     = GNUNET_NAMESTORE_zone_iteration_start (namestore_handle,
744                                              NULL, /* All zones */
745                                              &zone_iteration_error,
746                                              NULL,
747                                              &put_gns_record,
748                                              NULL,
749                                              &zone_iteration_finished,
750                                              NULL);
751 }
752
753
754 /**
755  * Process a record that was stored in the namestore
756  * (invoked by the monitor).
757  *
758  * @param cls closure, NULL
759  * @param zone private key of the zone; NULL on disconnect
760  * @param label label of the records; NULL on disconnect
761  * @param rd_count number of entries in @a rd array, 0 if label was deleted
762  * @param rd array of records with data to store
763  */
764 static void
765 handle_monitor_event (void *cls,
766                       const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
767                       const char *label,
768                       unsigned int rd_count,
769                       const struct GNUNET_GNSRECORD_Data *rd)
770 {
771   struct GNUNET_GNSRECORD_Data rd_public[rd_count];
772   unsigned int rd_public_count;
773   struct MonitorActivity *ma;
774
775   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
776               "Received %u records for label `%s' via namestore monitor\n",
777               rd_count,
778               label);
779   /* filter out records that are not public, and convert to
780      absolute expiration time. */
781   rd_public_count = convert_records_for_export (rd,
782                                                 rd_count,
783                                                 rd_public);
784   if (0 == rd_public_count)
785     return; /* nothing to do */
786   ma = GNUNET_new (struct MonitorActivity);
787   ma->ph = perform_dht_put (zone,
788                             label,
789                             rd,
790                             rd_count,
791                             ma);
792   if (NULL == ma->ph)
793   {
794     /* PUT failed, do not remember operation */
795     GNUNET_free (ma);
796     return;
797   }
798   GNUNET_CONTAINER_DLL_insert (ma_head,
799                                ma_tail,
800                                ma);
801 }
802
803
804 /* END DHT ZONE PROPAGATION */
805
806
807 /**
808  * Reply to client with the result from our lookup.
809  *
810  * @param cls the closure (our client lookup handle)
811  * @param rd_count the number of records in @a rd
812  * @param rd the record data
813  */
814 static void
815 send_lookup_response (void* cls,
816                       uint32_t rd_count,
817                       const struct GNUNET_GNSRECORD_Data *rd)
818 {
819   struct ClientLookupHandle *clh = cls;
820   struct GNUNET_MQ_Envelope *env;
821   struct LookupResultMessage *rmsg;
822   size_t len;
823
824   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
825               "Sending LOOKUP_RESULT message with %u results\n",
826               (unsigned int) rd_count);
827
828   len = GNUNET_GNSRECORD_records_get_size (rd_count, rd);
829   env = GNUNET_MQ_msg_extra (rmsg,
830                              len,
831                              GNUNET_MESSAGE_TYPE_GNS_LOOKUP_RESULT);
832   rmsg->id = clh->request_id;
833   rmsg->rd_count = htonl (rd_count);
834   GNUNET_GNSRECORD_records_serialize (rd_count, rd, len,
835                                       (char*) &rmsg[1]);
836   GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq(clh->gc->client),
837                   env);
838   GNUNET_CONTAINER_DLL_remove (clh->gc->clh_head, clh->gc->clh_tail, clh);
839   GNUNET_free (clh);
840   GNUNET_STATISTICS_update (statistics,
841                             "Completed lookups", 1,
842                             GNUNET_NO);
843   GNUNET_STATISTICS_update (statistics,
844                             "Records resolved",
845                             rd_count,
846                             GNUNET_NO);
847 }
848
849
850 /**
851  * Checks a #GNUNET_MESSAGE_TYPE_GNS_LOOKUP message
852  *
853  * @param cls client sending the message
854  * @param l_msg message of type `struct LookupMessage`
855  * @return #GNUNET_OK if @a l_msg is well-formed
856  */
857 static int
858 check_lookup (void *cls,
859                     const struct LookupMessage *l_msg)
860 {
861   size_t msg_size;
862   const char* name;
863
864   msg_size = ntohs (l_msg->header.size);
865   if (msg_size < sizeof (struct LookupMessage))
866   {
867     GNUNET_break (0);
868     return GNUNET_SYSERR;
869   }
870   name = (const char *) &l_msg[1];
871   if ( ('\0' != name[msg_size - sizeof (struct LookupMessage) - 1]) ||
872        (strlen (name) > GNUNET_DNSPARSER_MAX_NAME_LENGTH) )
873   {
874     GNUNET_break (0);
875     return GNUNET_SYSERR;
876   }
877   return GNUNET_OK;
878 }
879
880 /**
881  * Handle lookup requests from client
882  *
883  * @param cls the closure
884  * @param client the client
885  * @param message the message
886  */
887 static void
888 handle_lookup (void *cls,
889                const struct LookupMessage *sh_msg)
890 {
891   struct GnsClient *gc = cls;
892   char name[GNUNET_DNSPARSER_MAX_NAME_LENGTH + 1];
893   struct ClientLookupHandle *clh;
894   char *nameptr = name;
895   const char *utf_in;
896   const struct GNUNET_CRYPTO_EcdsaPrivateKey *key;
897
898   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
899               "Received LOOKUP message\n");
900   GNUNET_SERVICE_client_continue (gc->client);
901   if (GNUNET_YES == ntohs (sh_msg->have_key))
902     key = &sh_msg->shorten_key;
903   else
904     key = NULL;
905   utf_in = (const char *) &sh_msg[1];
906   GNUNET_STRINGS_utf8_tolower (utf_in, nameptr);
907
908   clh = GNUNET_new (struct ClientLookupHandle);
909   GNUNET_CONTAINER_DLL_insert (gc->clh_head, gc->clh_tail, clh);
910   clh->gc = gc;
911   clh->request_id = sh_msg->id;
912   if ( (GNUNET_DNSPARSER_TYPE_A == ntohl (sh_msg->type)) &&
913        (GNUNET_OK != v4_enabled) )
914   {
915     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
916                 "LOOKUP: Query for A record but AF_INET not supported!");
917     send_lookup_response (clh, 0, NULL);
918     return;
919   }
920   if ( (GNUNET_DNSPARSER_TYPE_AAAA == ntohl (sh_msg->type)) &&
921        (GNUNET_OK != v6_enabled) )
922   {
923     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
924                 "LOOKUP: Query for AAAA record but AF_INET6 not supported!");
925     send_lookup_response (clh, 0, NULL);
926     return;
927   }
928   clh->lookup = GNS_resolver_lookup (&sh_msg->zone,
929                                      ntohl (sh_msg->type),
930                                      name,
931                                      key,
932                                      (enum GNUNET_GNS_LocalOptions) ntohs (sh_msg->options),
933                                      &send_lookup_response, clh);
934   GNUNET_STATISTICS_update (statistics,
935                             "Lookup attempts",
936                             1, GNUNET_NO);
937 }
938
939
940 /**
941  * The zone monitor is now in SYNC with the current state of the
942  * name store.  Start to perform periodic iterations.
943  *
944  * @param cls NULL
945  */
946 static void
947 monitor_sync_event (void *cls)
948 {
949   GNUNET_assert (NULL == zone_publish_task);
950   zone_publish_task = GNUNET_SCHEDULER_add_now (&publish_zone_dht_start,
951                                                 NULL);
952 }
953
954
955 /**
956  * The zone monitor is now in SYNC with the current state of the
957  * name store.  Start to perform periodic iterations.
958  *
959  * @param cls NULL
960  */
961 static void
962 handle_monitor_error (void *cls)
963 {
964   if (NULL != zone_publish_task)
965   {
966     GNUNET_SCHEDULER_cancel (zone_publish_task);
967     zone_publish_task = NULL;
968   }
969   if (NULL != namestore_iter)
970   {
971     GNUNET_NAMESTORE_zone_iteration_stop (namestore_iter);
972     namestore_iter = NULL;
973   }
974   if (NULL != active_put)
975   {
976     GNUNET_DHT_put_cancel (active_put);
977     active_put = NULL;
978   }
979   zone_publish_task = GNUNET_SCHEDULER_add_now (&publish_zone_dht_start,
980                                                 NULL);
981 }
982
983
984 /**
985  * Method called to inform about the ego to be used for the master zone
986  * for DNS interceptions.
987  *
988  * This function is only called ONCE, and 'NULL' being passed in
989  * @a ego does indicate that interception is not configured.
990  * If @a ego is non-NULL, we should start to intercept DNS queries
991  * and resolve ".gnu" queries using the given ego as the master zone.
992  *
993  * @param cls closure, our `const struct GNUNET_CONFIGURATION_Handle *c`
994  * @param ego ego handle
995  * @param ctx context for application to store data for this ego
996  *                 (during the lifetime of this process, initially NULL)
997  * @param name name assigned by the user for this ego,
998  *                   NULL if the user just deleted the ego and it
999  *                   must thus no longer be used
1000  */
1001 static void
1002 identity_intercept_cb (void *cls,
1003                        struct GNUNET_IDENTITY_Ego *ego,
1004                        void **ctx,
1005                        const char *name)
1006 {
1007   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
1008   struct GNUNET_CRYPTO_EcdsaPublicKey dns_root;
1009
1010   identity_op = NULL;
1011   if (NULL == ego)
1012   {
1013     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1014                 _("No ego configured for `%s`\n"),
1015                 "gns-intercept");
1016     return;
1017   }
1018   GNUNET_IDENTITY_ego_get_public_key (ego,
1019                                       &dns_root);
1020   if (GNUNET_SYSERR ==
1021       GNS_interceptor_init (&dns_root, cfg))
1022   {
1023     GNUNET_break (0);
1024     GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
1025     return;
1026   }
1027 }
1028
1029
1030 /**
1031  * Process GNS requests.
1032  *
1033  * @param cls closure
1034  * @param server the initialized server
1035  * @param c configuration to use
1036  */
1037 static void
1038 run (void *cls,
1039      const struct GNUNET_CONFIGURATION_Handle *c,
1040      struct GNUNET_SERVICE_Handle *service)
1041 {
1042   unsigned long long max_parallel_bg_queries = 0;
1043
1044   v6_enabled = GNUNET_NETWORK_test_pf (PF_INET6);
1045   v4_enabled = GNUNET_NETWORK_test_pf (PF_INET);
1046   min_relative_record_time = GNUNET_TIME_UNIT_FOREVER_REL;
1047   namestore_handle = GNUNET_NAMESTORE_connect (c);
1048   if (NULL == namestore_handle)
1049   {
1050     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1051                 _("Failed to connect to the namestore!\n"));
1052     GNUNET_SCHEDULER_shutdown ();
1053     return;
1054   }
1055   namecache_handle = GNUNET_NAMECACHE_connect (c);
1056   if (NULL == namecache_handle)
1057   {
1058     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1059                 _("Failed to connect to the namecache!\n"));
1060     GNUNET_SCHEDULER_shutdown ();
1061     return;
1062   }
1063
1064   put_interval = INITIAL_PUT_INTERVAL;
1065   zone_publish_time_window_default = DEFAULT_ZONE_PUBLISH_TIME_WINDOW;
1066   if (GNUNET_OK ==
1067       GNUNET_CONFIGURATION_get_value_time (c, "gns",
1068                                            "ZONE_PUBLISH_TIME_WINDOW",
1069                                            &zone_publish_time_window_default))
1070   {
1071     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1072                 "Time window for zone iteration: %s\n",
1073                 GNUNET_STRINGS_relative_time_to_string (zone_publish_time_window,
1074                                                         GNUNET_YES));
1075   }
1076   zone_publish_time_window = zone_publish_time_window_default;
1077   if (GNUNET_OK ==
1078       GNUNET_CONFIGURATION_get_value_number (c, "gns",
1079                                              "MAX_PARALLEL_BACKGROUND_QUERIES",
1080                                              &max_parallel_bg_queries))
1081   {
1082     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1083                 "Number of allowed parallel background queries: %llu\n",
1084                 max_parallel_bg_queries);
1085   }
1086
1087   dht_handle = GNUNET_DHT_connect (c,
1088                                    (unsigned int) max_parallel_bg_queries);
1089   if (NULL == dht_handle)
1090   {
1091     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1092                 _("Could not connect to DHT!\n"));
1093     GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
1094     return;
1095   }
1096
1097   identity_handle = GNUNET_IDENTITY_connect (c,
1098                                              NULL,
1099                                              NULL);
1100   if (NULL == identity_handle)
1101   {
1102     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1103                 "Could not connect to identity service!\n");
1104   }
1105   else
1106   {
1107     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1108                 "Looking for gns-intercept ego\n");
1109     identity_op = GNUNET_IDENTITY_get (identity_handle,
1110                                        "gns-intercept",
1111                                        &identity_intercept_cb,
1112                                        (void *) c);
1113   }
1114   GNS_resolver_init (namecache_handle,
1115                      dht_handle,
1116                      c,
1117                      max_parallel_bg_queries);
1118   GNS_shorten_init (namestore_handle,
1119                     namecache_handle,
1120                     dht_handle);
1121   /* Schedule periodic put for our records. */
1122   first_zone_iteration = GNUNET_YES;
1123   statistics = GNUNET_STATISTICS_create ("gns", c);
1124   zmon = GNUNET_NAMESTORE_zone_monitor_start (c,
1125                                               NULL,
1126                                               GNUNET_NO,
1127                                               &handle_monitor_error,
1128                                               NULL,
1129                                               &handle_monitor_event,
1130                                               NULL,
1131                                               &monitor_sync_event,
1132                                               NULL);
1133   GNUNET_break (NULL != zmon);
1134   GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL);
1135 }
1136
1137
1138 /**
1139  * Define "main" method using service macro.
1140  */
1141 GNUNET_SERVICE_MAIN
1142 ("gns",
1143  GNUNET_SERVICE_OPTION_NONE,
1144  &run,
1145  &client_connect_cb,
1146  &client_disconnect_cb,
1147  NULL,
1148  GNUNET_MQ_hd_var_size (lookup,
1149                         GNUNET_MESSAGE_TYPE_GNS_LOOKUP,
1150                         struct LookupMessage,
1151                         NULL),
1152  GNUNET_MQ_handler_end());
1153
1154
1155 /* end of gnunet-service-gns.c */