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