4495bb6b787b101d4786a2bc3c213655006b2cdf
[oweals/gnunet.git] / src / gns / gnunet-service-gns.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2011-2013 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20 /**
21  * @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                const struct GNUNET_SCHEDULER_TaskContext *tc)
265 {
266   struct ClientLookupHandle *clh;
267   struct MonitorActivity *ma;
268
269   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
270               "Shutting down!\n");
271   GNUNET_SERVER_notification_context_destroy (nc);
272   while (NULL != (clh = clh_head))
273   {
274     GNUNET_SERVER_client_set_user_context (clh->client, NULL);
275     GNS_resolver_lookup_cancel (clh->lookup);
276     GNUNET_CONTAINER_DLL_remove (clh_head, clh_tail, clh);
277     GNUNET_free (clh);
278   }
279
280   GNS_interceptor_done ();
281   if (NULL != identity_op)
282   {
283     GNUNET_IDENTITY_cancel (identity_op);
284     identity_op = NULL;
285   }
286   if (NULL != identity_handle)
287   {
288     GNUNET_IDENTITY_disconnect (identity_handle);
289     identity_handle = NULL;
290   }
291   GNS_resolver_done ();
292   GNS_shorten_done ();
293   while (NULL != (ma = ma_head))
294   {
295     GNUNET_DHT_put_cancel (ma->ph);
296     GNUNET_CONTAINER_DLL_remove (ma_head,
297                                  ma_tail,
298                                  ma);
299     GNUNET_free (ma);
300   }
301   if (NULL != statistics)
302   {
303     GNUNET_STATISTICS_destroy (statistics, GNUNET_NO);
304     statistics = NULL;
305   }
306   if (NULL != zone_publish_task)
307   {
308     GNUNET_SCHEDULER_cancel (zone_publish_task);
309     zone_publish_task = NULL;
310   }
311   if (NULL != namestore_iter)
312   {
313     GNUNET_NAMESTORE_zone_iteration_stop (namestore_iter);
314     namestore_iter = NULL;
315   }
316   if (NULL != zmon)
317   {
318     GNUNET_NAMESTORE_zone_monitor_stop (zmon);
319     zmon = NULL;
320   }
321   if (NULL != namestore_handle)
322   {
323     GNUNET_NAMESTORE_disconnect (namestore_handle);
324     namestore_handle = NULL;
325   }
326   if (NULL != namecache_handle)
327   {
328     GNUNET_NAMECACHE_disconnect (namecache_handle);
329     namecache_handle = NULL;
330   }
331   if (NULL != active_put)
332   {
333     GNUNET_DHT_put_cancel (active_put);
334     active_put = NULL;
335   }
336   if (NULL != dht_handle)
337   {
338     GNUNET_DHT_disconnect (dht_handle);
339     dht_handle = NULL;
340   }
341 }
342
343
344 /**
345  * Method called periodically that triggers iteration over authoritative records
346  *
347  * @param cls closure
348  * @param tc task context
349  */
350 static void
351 publish_zone_dht_next (void *cls,
352                        const struct GNUNET_SCHEDULER_TaskContext *tc)
353 {
354   zone_publish_task = NULL;
355   GNUNET_NAMESTORE_zone_iterator_next (namestore_iter);
356 }
357
358
359 /**
360  * Periodically iterate over our zone and store everything in dht
361  *
362  * @param cls NULL
363  * @param tc task context
364  */
365 static void
366 publish_zone_dht_start (void *cls,
367                         const struct GNUNET_SCHEDULER_TaskContext *tc);
368
369
370 /**
371  * Continuation called from DHT once the PUT operation is done.
372  *
373  * @param cls closure, NULL if called from regular iteration,
374  *        `struct MonitorActivity` if called from #handle_monitor_event.
375  * @param success #GNUNET_OK on success
376  */
377 static void
378 dht_put_continuation (void *cls,
379                       int success)
380 {
381   struct MonitorActivity *ma = cls;
382   struct GNUNET_TIME_Relative next_put_interval;
383
384   num_public_records++;
385   if (NULL == ma)
386   {
387     active_put = NULL;
388     if ( (num_public_records > last_num_public_records) &&
389          (GNUNET_NO == first_zone_iteration) )
390     {
391       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
392                   "Last record count was lower than current record count.  Reducing interval.\n");
393       put_interval = GNUNET_TIME_relative_divide (zone_publish_time_window,
394                                                   num_public_records);
395       next_put_interval = GNUNET_TIME_relative_divide (put_interval,
396                                                        LATE_ITERATION_SPEEDUP_FACTOR);
397     }
398     else
399       next_put_interval = put_interval;
400
401     GNUNET_STATISTICS_set (statistics,
402                            "Current zone iteration interval (ms)",
403                            next_put_interval.rel_value_us / 1000LL,
404                            GNUNET_NO);
405     zone_publish_task = GNUNET_SCHEDULER_add_delayed (next_put_interval,
406                                                       &publish_zone_dht_next,
407                                                       NULL);
408   }
409   else
410   {
411     GNUNET_CONTAINER_DLL_remove (ma_head,
412                                  ma_tail,
413                                  ma);
414     GNUNET_free (ma);
415   }
416 }
417
418
419 /**
420  * Convert namestore records from the internal format to that
421  * suitable for publication (removes private records, converts
422  * to absolute expiration time).
423  *
424  * @param rd input records
425  * @param rd_count size of the @a rd and @a rd_public arrays
426  * @param rd_public where to write the converted records
427  * @return number of records written to @a rd_public
428  */
429 static unsigned int
430 convert_records_for_export (const struct GNUNET_GNSRECORD_Data *rd,
431                             unsigned int rd_count,
432                             struct GNUNET_GNSRECORD_Data *rd_public)
433 {
434   struct GNUNET_TIME_Absolute now;
435   unsigned int rd_public_count;
436   unsigned int i;
437
438   rd_public_count = 0;
439   now = GNUNET_TIME_absolute_get ();
440   for (i=0;i<rd_count;i++)
441     if (0 == (rd[i].flags & GNUNET_GNSRECORD_RF_PRIVATE))
442     {
443       rd_public[rd_public_count] = rd[i];
444       if (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION))
445       {
446         /* GNUNET_GNSRECORD_block_create will convert to absolute time;
447            we just need to adjust our iteration frequency */
448         min_relative_record_time.rel_value_us =
449           GNUNET_MIN (rd_public[rd_public_count].expiration_time,
450                       min_relative_record_time.rel_value_us);
451       }
452       else if (rd_public[rd_public_count].expiration_time < now.abs_value_us)
453       {
454         /* record already expired, skip it */
455         continue;
456       }
457       rd_public_count++;
458     }
459   return rd_public_count;
460 }
461
462
463 /**
464  * Store GNS records in the DHT.
465  *
466  * @param key key of the zone
467  * @param label label to store under
468  * @param rd_public public record data
469  * @param rd_public_count number of records in @a rd_public
470  * @param pc_arg closure argument to pass to the #dht_put_continuation
471  * @return DHT PUT handle, NULL on error
472  */
473 static struct GNUNET_DHT_PutHandle *
474 perform_dht_put (const struct GNUNET_CRYPTO_EcdsaPrivateKey *key,
475                  const char *label,
476                  const struct GNUNET_GNSRECORD_Data *rd_public,
477                  unsigned int rd_public_count,
478                  void *pc_arg)
479 {
480   struct GNUNET_GNSRECORD_Block *block;
481   struct GNUNET_HashCode query;
482   struct GNUNET_TIME_Absolute expire;
483   size_t block_size;
484   struct GNUNET_DHT_PutHandle *ret;
485
486   expire = GNUNET_GNSRECORD_record_get_expiration_time (rd_public_count,
487                                                         rd_public);
488   block = GNUNET_GNSRECORD_block_create (key,
489                                          expire,
490                                          label,
491                                          rd_public,
492                                          rd_public_count);
493   if (NULL == block)
494     return NULL; /* whoops */
495   block_size = ntohl (block->purpose.size)
496     + sizeof (struct GNUNET_CRYPTO_EcdsaSignature)
497     + sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey);
498   GNUNET_GNSRECORD_query_from_private_key (key,
499                                            label,
500                                            &query);
501   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
502               "Storing %u record(s) for label `%s' in DHT with expiration `%s' under key %s\n",
503               rd_public_count,
504               label,
505               GNUNET_STRINGS_absolute_time_to_string (expire),
506               GNUNET_h2s (&query));
507   ret = GNUNET_DHT_put (dht_handle, &query,
508                         DHT_GNS_REPLICATION_LEVEL,
509                         GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
510                         GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
511                         block_size,
512                         block,
513                         expire,
514                         DHT_OPERATION_TIMEOUT,
515                         &dht_put_continuation,
516                         pc_arg);
517   GNUNET_free (block);
518   return ret;
519 }
520
521
522 /**
523  * Function used to put all records successively into the DHT.
524  *
525  * @param cls the closure (NULL)
526  * @param key the private key of the authority (ours)
527  * @param label the name of the records, NULL once the iteration is done
528  * @param rd_count the number of records in @a rd
529  * @param rd the record data
530  */
531 static void
532 put_gns_record (void *cls,
533                 const struct GNUNET_CRYPTO_EcdsaPrivateKey *key,
534                 const char *label,
535                 unsigned int rd_count,
536                 const struct GNUNET_GNSRECORD_Data *rd)
537 {
538   struct GNUNET_GNSRECORD_Data rd_public[rd_count];
539   unsigned int rd_public_count;
540
541   if (NULL == label)
542   {
543     /* we're done with one iteration, calculate when to do the next one */
544     namestore_iter = NULL;
545     last_num_public_records = num_public_records;
546     first_zone_iteration = GNUNET_NO;
547     if (0 == num_public_records)
548     {
549       /**
550        * If no records are known (startup) or none present
551        * we can safely set the interval to the value for a single
552        * record
553        */
554       put_interval = zone_publish_time_window;
555       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
556                   "No records in namestore database.\n");
557     }
558     else
559     {
560       /* If records are present, next publication is based on the minimum
561        * relative expiration time of the records published divided by 4
562        */
563       zone_publish_time_window = GNUNET_TIME_relative_min (
564           GNUNET_TIME_relative_divide (min_relative_record_time, 4),
565           zone_publish_time_window_default);
566       put_interval = GNUNET_TIME_relative_divide (zone_publish_time_window,
567           num_public_records);
568     }
569     /* reset for next iteration */
570     min_relative_record_time = GNUNET_TIME_UNIT_FOREVER_REL;
571     put_interval = GNUNET_TIME_relative_max (MINIMUM_ZONE_ITERATION_INTERVAL,
572                                              put_interval);
573
574     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
575                 "Zone iteration finished. Adjusted zone iteration interval to %s\n",
576                 GNUNET_STRINGS_relative_time_to_string (put_interval, GNUNET_YES));
577     GNUNET_STATISTICS_set (statistics,
578                            "Current zone iteration interval (in ms)",
579                            put_interval.rel_value_us / 1000LL,
580                            GNUNET_NO);
581     GNUNET_STATISTICS_update (statistics,
582                               "Number of zone iterations",
583                               1,
584                               GNUNET_NO);
585     GNUNET_STATISTICS_set (statistics,
586                            "Number of public records in DHT",
587                            last_num_public_records,
588                            GNUNET_NO);
589     if (0 == num_public_records)
590       zone_publish_task = GNUNET_SCHEDULER_add_delayed (put_interval,
591                                                         &publish_zone_dht_start,
592                                                         NULL);
593     else
594       zone_publish_task = GNUNET_SCHEDULER_add_now (&publish_zone_dht_start,
595                                                     NULL);
596     return;
597   }
598
599   rd_public_count = convert_records_for_export (rd,
600                                                 rd_count,
601                                                 rd_public);
602
603   /* We got a set of records to publish */
604   if (0 == rd_public_count)
605   {
606     zone_publish_task = GNUNET_SCHEDULER_add_now (&publish_zone_dht_next,
607                                                    NULL);
608     return;
609   }
610
611   active_put = perform_dht_put (key,
612                                 label,
613                                 rd_public,
614                                 rd_public_count,
615                                 NULL);
616   if (NULL == active_put)
617   {
618     GNUNET_break (0);
619     dht_put_continuation (NULL, GNUNET_NO);
620   }
621 }
622
623
624 /**
625  * Periodically iterate over all zones and store everything in DHT
626  *
627  * @param cls NULL
628  * @param tc task context
629  */
630 static void
631 publish_zone_dht_start (void *cls,
632                         const struct GNUNET_SCHEDULER_TaskContext *tc)
633 {
634   zone_publish_task = NULL;
635
636   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
637               "Starting DHT zone update!\n");
638   /* start counting again */
639   num_public_records = 0;
640   namestore_iter = GNUNET_NAMESTORE_zone_iteration_start (namestore_handle,
641       NULL, /* All zones */
642       &put_gns_record, NULL );
643 }
644
645
646 /**
647  * Process a record that was stored in the namestore
648  * (invoked by the monitor).
649  *
650  * @param cls closure, NULL
651  * @param zone private key of the zone; NULL on disconnect
652  * @param label label of the records; NULL on disconnect
653  * @param rd_count number of entries in @a rd array, 0 if label was deleted
654  * @param rd array of records with data to store
655  */
656 static void
657 handle_monitor_event (void *cls,
658                       const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone,
659                       const char *label,
660                       unsigned int rd_count,
661                       const struct GNUNET_GNSRECORD_Data *rd)
662 {
663   struct GNUNET_GNSRECORD_Data rd_public[rd_count];
664   unsigned int rd_public_count;
665   struct MonitorActivity *ma;
666
667   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
668               "Received %u records for label `%s' via namestore monitor\n",
669               rd_count,
670               label);
671   /* filter out records that are not public, and convert to
672      absolute expiration time. */
673   rd_public_count = convert_records_for_export (rd, rd_count,
674                                                 rd_public);
675   if (0 == rd_public_count)
676     return; /* nothing to do */
677   ma = GNUNET_new (struct MonitorActivity);
678   ma->ph = perform_dht_put (zone, label,
679                             rd, rd_count,
680                             ma);
681   if (NULL == ma->ph)
682   {
683     /* PUT failed, do not remember operation */
684     GNUNET_free (ma);
685     return;
686   }
687   GNUNET_CONTAINER_DLL_insert (ma_head,
688                                ma_tail,
689                                ma);
690 }
691
692
693 /* END DHT ZONE PROPAGATION */
694
695
696 /**
697  * Reply to client with the result from our lookup.
698  *
699  * @param cls the closure (our client lookup handle)
700  * @param rd_count the number of records in @a rd
701  * @param rd the record data
702  */
703 static void
704 send_lookup_response (void* cls,
705                       uint32_t rd_count,
706                       const struct GNUNET_GNSRECORD_Data *rd)
707 {
708   struct ClientLookupHandle *clh = cls;
709   struct GNUNET_GNS_ClientLookupResultMessage *rmsg;
710   size_t len;
711
712   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
713               "Sending `%s' message with %d results\n",
714               "LOOKUP_RESULT",
715               rd_count);
716
717   len = GNUNET_GNSRECORD_records_get_size (rd_count, rd);
718   rmsg = GNUNET_malloc (len + sizeof (struct GNUNET_GNS_ClientLookupResultMessage));
719   rmsg->header.type = htons (GNUNET_MESSAGE_TYPE_GNS_LOOKUP_RESULT);
720   rmsg->header.size = htons (len + sizeof(struct GNUNET_GNS_ClientLookupResultMessage));
721   rmsg->id = clh->request_id;
722   rmsg->rd_count = htonl (rd_count);
723   GNUNET_GNSRECORD_records_serialize (rd_count, rd, len,
724                                       (char*) &rmsg[1]);
725   GNUNET_SERVER_notification_context_unicast (nc,
726                                               clh->client,
727                                               &rmsg->header,
728                                               GNUNET_NO);
729   GNUNET_free (rmsg);
730   GNUNET_CONTAINER_DLL_remove (clh_head, clh_tail, clh);
731   GNUNET_SERVER_client_set_user_context (clh->client, NULL);
732   GNUNET_free (clh);
733   GNUNET_STATISTICS_update (statistics,
734                             "Completed lookups", 1,
735                             GNUNET_NO);
736   GNUNET_STATISTICS_update (statistics,
737                             "Records resolved",
738                             rd_count,
739                             GNUNET_NO);
740 }
741
742
743 /**
744  * Handle lookup requests from client
745  *
746  * @param cls the closure
747  * @param client the client
748  * @param message the message
749  */
750 static void
751 handle_lookup (void *cls,
752                struct GNUNET_SERVER_Client *client,
753                const struct GNUNET_MessageHeader *message)
754 {
755   char name[GNUNET_DNSPARSER_MAX_NAME_LENGTH + 1];
756   struct ClientLookupHandle *clh;
757   char *nameptr = name;
758   const char *utf_in;
759   const struct GNUNET_CRYPTO_EcdsaPrivateKey *key;
760   uint16_t msg_size;
761   const struct GNUNET_GNS_ClientLookupMessage *sh_msg;
762
763   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
764               "Received `%s' message\n",
765               "LOOKUP");
766   msg_size = ntohs (message->size);
767   if (msg_size < sizeof (struct GNUNET_GNS_ClientLookupMessage))
768   {
769     GNUNET_break (0);
770     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
771     return;
772   }
773   sh_msg = (const struct GNUNET_GNS_ClientLookupMessage *) message;
774   GNUNET_SERVER_notification_context_add (nc, client);
775   if (GNUNET_YES == ntohs (sh_msg->have_key))
776     key = &sh_msg->shorten_key;
777   else
778     key = NULL;
779   utf_in = (const char *) &sh_msg[1];
780   if ( ('\0' != utf_in[msg_size - sizeof (struct GNUNET_GNS_ClientLookupMessage) - 1]) ||
781        (strlen (utf_in) > GNUNET_DNSPARSER_MAX_NAME_LENGTH) )
782   {
783     GNUNET_break (0);
784     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
785     return;
786   }
787   GNUNET_STRINGS_utf8_tolower (utf_in, nameptr);
788   GNUNET_SERVER_receive_done (client, GNUNET_OK);
789
790   clh = GNUNET_new (struct ClientLookupHandle);
791   GNUNET_SERVER_client_set_user_context (client, clh);
792   GNUNET_CONTAINER_DLL_insert (clh_head, clh_tail, clh);
793   clh->client = client;
794   clh->request_id = sh_msg->id;
795   if ( (GNUNET_DNSPARSER_TYPE_A == ntohl (sh_msg->type)) &&
796        (GNUNET_OK != v4_enabled) )
797   {
798     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
799                 "LOOKUP: Query for A record but AF_INET not supported!");
800     send_lookup_response (clh, 0, NULL);
801     return;
802   }
803   if ( (GNUNET_DNSPARSER_TYPE_AAAA == ntohl (sh_msg->type)) &&
804        (GNUNET_OK != v6_enabled) )
805   {
806     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
807                 "LOOKUP: Query for AAAA record but AF_INET6 not supported!");
808     send_lookup_response (clh, 0, NULL);
809     return;
810   }
811   clh->lookup = GNS_resolver_lookup (&sh_msg->zone,
812                                      ntohl (sh_msg->type),
813                                      name,
814                                      key,
815                                      (enum GNUNET_GNS_LocalOptions) ntohs (sh_msg->options),
816                                      &send_lookup_response, clh);
817   GNUNET_STATISTICS_update (statistics,
818                             "Lookup attempts",
819                             1, GNUNET_NO);
820 }
821
822
823 /**
824  * One of our clients disconnected, clean up after it.
825  *
826  * @param cls NULL
827  * @param client the client that disconnected
828  */
829 static void
830 notify_client_disconnect (void *cls,
831                           struct GNUNET_SERVER_Client *client)
832 {
833   struct ClientLookupHandle *clh;
834
835   if (NULL == client)
836     return;
837   clh = GNUNET_SERVER_client_get_user_context (client, struct ClientLookupHandle);
838   if (NULL == clh)
839     return;
840   GNS_resolver_lookup_cancel (clh->lookup);
841   GNUNET_CONTAINER_DLL_remove (clh_head, clh_tail, clh);
842   GNUNET_free (clh);
843 }
844
845
846 /**
847  * The zone monitor is now in SYNC with the current state of the
848  * name store.  Start to perform periodic iterations.
849  *
850  * @param cls NULL
851  */
852 static void
853 monitor_sync_event (void *cls)
854 {
855   zone_publish_task = GNUNET_SCHEDULER_add_now (&publish_zone_dht_start,
856                                                 NULL);
857 }
858
859
860 /**
861  * Method called to inform about the ego to be used for the master zone
862  * for DNS interceptions.
863  *
864  * This function is only called ONCE, and 'NULL' being passed in
865  * @a ego does indicate that interception is not configured.
866  * If @a ego is non-NULL, we should start to intercept DNS queries
867  * and resolve ".gnu" queries using the given ego as the master zone.
868  *
869  * @param cls closure, our `const struct GNUNET_CONFIGURATION_Handle *c`
870  * @param ego ego handle
871  * @param ctx context for application to store data for this ego
872  *                 (during the lifetime of this process, initially NULL)
873  * @param name name assigned by the user for this ego,
874  *                   NULL if the user just deleted the ego and it
875  *                   must thus no longer be used
876  */
877 static void
878 identity_intercept_cb (void *cls,
879                     struct GNUNET_IDENTITY_Ego *ego,
880                     void **ctx,
881                     const char *name)
882 {
883   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
884   struct GNUNET_CRYPTO_EcdsaPublicKey dns_root;
885
886   identity_op = NULL;
887   if (NULL == ego)
888   {
889     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
890                 _("No ego configured for `%s`\n"),
891                 "gns-intercept");
892     return;
893   }
894   GNUNET_IDENTITY_ego_get_public_key (ego,
895                                       &dns_root);
896   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
897               "DNS hijacking enabled. Connecting to DNS service.\n");
898   if (GNUNET_SYSERR ==
899       GNS_interceptor_init (&dns_root, cfg))
900   {
901     GNUNET_break (0);
902     GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
903     return;
904   }
905 }
906
907
908 /**
909  * Process GNS requests.
910  *
911  * @param cls closure
912  * @param server the initialized server
913  * @param c configuration to use
914  */
915 static void
916 run (void *cls,
917      struct GNUNET_SERVER_Handle *server,
918      const struct GNUNET_CONFIGURATION_Handle *c)
919 {
920   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
921     { &handle_lookup, NULL, GNUNET_MESSAGE_TYPE_GNS_LOOKUP, 0},
922     {NULL, NULL, 0, 0}
923   };
924   unsigned long long max_parallel_bg_queries = 0;
925
926   v6_enabled = GNUNET_NETWORK_test_pf (PF_INET6);
927   v4_enabled = GNUNET_NETWORK_test_pf (PF_INET);
928   min_relative_record_time = GNUNET_TIME_UNIT_FOREVER_REL;
929   namestore_handle = GNUNET_NAMESTORE_connect (c);
930   if (NULL == namestore_handle)
931   {
932     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
933                 _("Failed to connect to the namestore!\n"));
934     GNUNET_SCHEDULER_shutdown ();
935     return;
936   }
937   namecache_handle = GNUNET_NAMECACHE_connect (c);
938   if (NULL == namecache_handle)
939   {
940     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
941                 _("Failed to connect to the namecache!\n"));
942     GNUNET_SCHEDULER_shutdown ();
943     return;
944   }
945
946   put_interval = INITIAL_PUT_INTERVAL;
947   zone_publish_time_window_default = DEFAULT_ZONE_PUBLISH_TIME_WINDOW;
948   if (GNUNET_OK ==
949       GNUNET_CONFIGURATION_get_value_time (c, "gns",
950                                            "ZONE_PUBLISH_TIME_WINDOW",
951                                            &zone_publish_time_window_default))
952   {
953     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
954                 "Time window for zone iteration: %s\n",
955                 GNUNET_STRINGS_relative_time_to_string (zone_publish_time_window,
956                                                         GNUNET_YES));
957   }
958   zone_publish_time_window = zone_publish_time_window_default;
959   if (GNUNET_OK ==
960       GNUNET_CONFIGURATION_get_value_number (c, "gns",
961                                             "MAX_PARALLEL_BACKGROUND_QUERIES",
962                                             &max_parallel_bg_queries))
963   {
964     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
965                 "Number of allowed parallel background queries: %llu\n",
966                 max_parallel_bg_queries);
967   }
968
969   dht_handle = GNUNET_DHT_connect (c,
970                                    (unsigned int) max_parallel_bg_queries);
971   if (NULL == dht_handle)
972   {
973     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
974                 _("Could not connect to DHT!\n"));
975     GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
976     return;
977   }
978
979   identity_handle = GNUNET_IDENTITY_connect (c,
980                                              NULL,
981                                              NULL);
982   if (NULL == identity_handle)
983   {
984     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
985                 "Could not connect to identity service!\n");
986   }
987   else
988   {
989     identity_op = GNUNET_IDENTITY_get (identity_handle,
990                                        "gns-intercept",
991                                        &identity_intercept_cb,
992                                        (void *) c);
993   }
994   GNS_resolver_init (namecache_handle,
995                      dht_handle,
996                      c,
997                      max_parallel_bg_queries);
998   GNS_shorten_init (namestore_handle,
999                     namecache_handle,
1000                     dht_handle);
1001   GNUNET_SERVER_disconnect_notify (server,
1002                                    &notify_client_disconnect,
1003                                    NULL);
1004   /* Schedule periodic put for our records. */
1005   first_zone_iteration = GNUNET_YES;
1006   GNUNET_SERVER_add_handlers (server, handlers);
1007   statistics = GNUNET_STATISTICS_create ("gns", c);
1008   nc = GNUNET_SERVER_notification_context_create (server, 1);
1009   zmon = GNUNET_NAMESTORE_zone_monitor_start (c,
1010                                               NULL,
1011                                               GNUNET_NO,
1012                                               &handle_monitor_event,
1013                                               &monitor_sync_event,
1014                                               NULL);
1015   GNUNET_break (NULL != zmon);
1016   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1017                                 &shutdown_task, NULL);
1018 }
1019
1020
1021 /**
1022  * The main function for the GNS service.
1023  *
1024  * @param argc number of arguments from the command line
1025  * @param argv command line arguments
1026  * @return 0 ok, 1 on error
1027  */
1028 int
1029 main (int argc, char *const *argv)
1030 {
1031   int ret;
1032
1033   ret =
1034       (GNUNET_OK ==
1035        GNUNET_SERVICE_run (argc, argv, "gns", GNUNET_SERVICE_OPTION_NONE, &run,
1036                            NULL)) ? 0 : 1;
1037   return ret;
1038 }
1039
1040 /* end of gnunet-service-gns.c */