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