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