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