-moving code to new libgnunetgnsrecord in preparation for addressing #3052
[oweals/gnunet.git] / src / gns / gnunet-service-gns_resolver.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 /**
22  * @file gns/gnunet-service-gns_resolver.c
23  * @brief GNU Name System resolver logic
24  * @author Martin Schanzenbach
25  * @author Christian Grothoff
26  *
27  * TODO:
28  * - GNS: handle special SRV names --- no delegation, direct lookup;
29  *        can likely be done in 'resolver_lookup_get_next_label'. (#3003)
30  * - revocation checks (use CORE-level broadcasts!), (#3004)
31  * - DNAME support (#3005)
32  */
33 #include "platform.h"
34 #include "gnunet_util_lib.h"
35 #include "gnunet_dnsstub_lib.h"
36 #include "gnunet_dht_service.h"
37 #include "gnunet_gnsrecord_lib.h"
38 #include "gnunet_namestore_service.h"
39 #include "gnunet_dns_service.h"
40 #include "gnunet_resolver_service.h"
41 #include "gnunet_dnsparser_lib.h"
42 #include "gnunet_gns_service.h"
43 #include "gns.h"
44 #include "gnunet-service-gns_resolver.h"
45 #include "gnunet-service-gns_shorten.h"
46 #include "gnunet_vpn_service.h"
47
48
49 /**
50  * Default DHT timeout for lookups.
51  */
52 #define DHT_LOOKUP_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
53
54 /**
55  * Default timeout for DNS lookups.
56  */
57 #define DNS_LOOKUP_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
58
59 /**
60  * Default timeout for VPN redirections.
61  */
62 #define VPN_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 30)
63
64 /**
65  * DHT replication level
66  */
67 #define DHT_GNS_REPLICATION_LEVEL 5
68
69 /**
70  * How deep do we allow recursions to go before we abort?
71  */
72 #define MAX_RECURSION 256
73
74
75 /**
76  * DLL to hold the authority chain we had to pass in the resolution
77  * process.
78  */
79 struct AuthorityChain
80 {
81   /**
82    * This is a DLL.
83    */
84   struct AuthorityChain *prev;
85
86   /**
87    * This is a DLL.
88    */
89   struct AuthorityChain *next;
90
91   /**
92    * Resolver handle this entry in the chain belongs to.
93    */
94   struct GNS_ResolverHandle *rh;
95
96   /**
97    * label/name corresponding to the authority
98    */
99   char *label;
100
101   /**
102    * #GNUNET_YES if the authority was a GNS authority,
103    * #GNUNET_NO if the authority was a DNS authority.
104    */
105   int gns_authority;
106
107   /**
108    * Information about the resolver authority for this label.
109    */
110   union
111   {
112
113     /**
114      * The zone of the GNS authority
115      */
116     struct GNUNET_CRYPTO_EcdsaPublicKey gns_authority;
117
118     struct
119     {
120       /**
121        * Domain of the DNS resolver that is the authority.
122        * (appended to construct the DNS name to resolve;
123        * this is NOT the DNS name of the DNS server!).
124        */
125       char name[GNUNET_DNSPARSER_MAX_NAME_LENGTH + 1];
126
127       /**
128        * IP address of the DNS resolver that is authoritative.
129        * (this implementation currently only supports one
130        * IP at a time).
131        */
132       struct sockaddr_storage dns_ip;
133
134     } dns_authority;
135
136   } authority_info;
137
138 };
139
140
141 /**
142  * A result we got from DNS.
143  */
144 struct DnsResult
145 {
146
147   /**
148    * Kept in DLL.
149    */
150   struct DnsResult *next;
151
152   /**
153    * Kept in DLL.
154    */
155   struct DnsResult *prev;
156
157   /**
158    * Binary value stored in the DNS record (appended to this struct)
159    */
160   const void *data;
161
162   /**
163    * Expiration time for the DNS record, 0 if we didn't
164    * get anything useful (i.e. 'gethostbyname' was used).
165    */
166   uint64_t expiration_time;
167
168   /**
169    * Number of bytes in 'data'.
170    */
171   size_t data_size;
172
173   /**
174    * Type of the GNS/DNS record.
175    */
176   uint32_t record_type;
177
178 };
179
180
181 /**
182  * Closure for #vpn_allocation_cb.
183  */
184 struct VpnContext
185 {
186
187   /**
188    * Which resolution process are we processing.
189    */
190   struct GNS_ResolverHandle *rh;
191
192   /**
193    * Handle to the VPN request that we were performing.
194    */
195   struct GNUNET_VPN_RedirectionRequest *vpn_request;
196
197   /**
198    * Number of records serialized in 'rd_data'.
199    */
200   unsigned int rd_count;
201
202   /**
203    * Serialized records.
204    */
205   char *rd_data;
206
207   /**
208    * Number of bytes in 'rd_data'.
209    */
210   size_t rd_data_size;
211 };
212
213
214 /**
215  * Handle to a currenty pending resolution.  On result (positive or
216  * negative) the #GNS_ResultProcessor is called.
217  */
218 struct GNS_ResolverHandle
219 {
220
221   /**
222    * DLL
223    */
224   struct GNS_ResolverHandle *next;
225
226   /**
227    * DLL
228    */
229   struct GNS_ResolverHandle *prev;
230
231   /**
232    * The top-level GNS authoritative zone to query
233    */
234   struct GNUNET_CRYPTO_EcdsaPublicKey authority_zone;
235
236   /**
237    * called when resolution phase finishes
238    */
239   GNS_ResultProcessor proc;
240
241   /**
242    * closure passed to proc
243    */
244   void* proc_cls;
245
246   /**
247    * Handle for DHT lookups. should be NULL if no lookups are in progress
248    */
249   struct GNUNET_DHT_GetHandle *get_handle;
250
251   /**
252    * Handle to a VPN request, NULL if none is active.
253    */
254   struct VpnContext *vpn_ctx;
255
256   /**
257    * Socket for a DNS request, NULL if none is active.
258    */
259   struct GNUNET_DNSSTUB_RequestSocket *dns_request;
260
261   /**
262    * Handle for standard DNS resolution, NULL if none is active.
263    */
264   struct GNUNET_RESOLVER_RequestHandle *std_resolve;
265
266   /**
267    * Pending Namestore lookup task
268    */
269   struct GNUNET_NAMESTORE_QueueEntry *namestore_qe;
270
271   /**
272    * Heap node associated with this lookup.  Used to limit number of
273    * concurrent requests.
274    */
275   struct GNUNET_CONTAINER_HeapNode *dht_heap_node;
276
277   /**
278    * DLL to store the authority chain
279    */
280   struct AuthorityChain *ac_head;
281
282   /**
283    * DLL to store the authority chain
284    */
285   struct AuthorityChain *ac_tail;
286
287   /**
288    * Private key of the shorten zone, NULL to not shorten.
289    */
290   struct GNUNET_CRYPTO_EcdsaPrivateKey *shorten_key;
291
292   /**
293    * ID of a task associated with the resolution process.
294    */
295   GNUNET_SCHEDULER_TaskIdentifier task_id;
296
297   /**
298    * The name to resolve
299    */
300   char *name;
301
302   /**
303    * DLL of results we got from DNS.
304    */
305   struct DnsResult *dns_result_head;
306
307   /**
308    * DLL of results we got from DNS.
309    */
310   struct DnsResult *dns_result_tail;
311
312   /**
313    * Current offset in 'name' where we are resolving.
314    */
315   size_t name_resolution_pos;
316
317   /**
318    * Use only cache
319    */
320   int only_cached;
321
322   /**
323    * Desired type for the resolution.
324    */
325   int record_type;
326
327   /**
328    * We increment the loop limiter for each step in a recursive
329    * resolution.  If it passes our threshold (i.e. due to
330    * self-recursion in the resolution, i.e CNAME fun), we stop.
331    */
332   unsigned int loop_limiter;
333
334 };
335
336
337 /**
338  * Active namestore caching operations.
339  */
340 struct CacheOps
341 {
342
343   /**
344    * Organized in a DLL.
345    */
346   struct CacheOps *next;
347
348   /**
349    * Organized in a DLL.
350    */
351   struct CacheOps *prev;
352
353   /**
354    * Pending Namestore caching task.
355    */
356   struct GNUNET_NAMESTORE_QueueEntry *namestore_qe_cache;
357
358 };
359
360
361 /**
362  * Our handle to the namestore service
363  */
364 static struct GNUNET_NAMESTORE_Handle *namestore_handle;
365
366 /**
367  * Our handle to the vpn service
368  */
369 static struct GNUNET_VPN_Handle *vpn_handle;
370
371 /**
372  * Resolver handle to the dht
373  */
374 static struct GNUNET_DHT_Handle *dht_handle;
375
376 /**
377  * Handle to perform DNS lookups.
378  */
379 static struct GNUNET_DNSSTUB_Context *dns_handle;
380
381 /**
382  * Heap for limiting parallel DHT lookups
383  */
384 static struct GNUNET_CONTAINER_Heap *dht_lookup_heap;
385
386 /**
387  * Maximum amount of parallel queries to the DHT
388  */
389 static unsigned long long max_allowed_background_queries;
390
391 /**
392  * Head of resolver lookup list
393  */
394 static struct GNS_ResolverHandle *rlh_head;
395
396 /**
397  * Tail of resolver lookup list
398  */
399 static struct GNS_ResolverHandle *rlh_tail;
400
401 /**
402  * Organized in a DLL.
403  */
404 static struct CacheOps *co_head;
405
406 /**
407  * Organized in a DLL.
408  */
409 static struct CacheOps *co_tail;
410
411
412 /**
413  * Global configuration.
414  */
415 static const struct GNUNET_CONFIGURATION_Handle *cfg;
416
417 #if 0
418 /**
419  * Check if name is in srv format (_x._y.xxx)
420  *
421  * @param name
422  * @return #GNUNET_YES if true
423  */
424 static int
425 is_srv (const char *name)
426 {
427   char *ndup;
428   int ret;
429
430   if (*name != '_')
431     return GNUNET_NO;
432   if (NULL == strstr (name, "._"))
433     return GNUNET_NO;
434   ret = GNUNET_YES;
435   ndup = GNUNET_strdup (name);
436   strtok (ndup, ".");
437   if (NULL == strtok (NULL, "."))
438     ret = GNUNET_NO;
439   if (NULL == strtok (NULL, "."))
440     ret = GNUNET_NO;
441   if (NULL != strtok (NULL, "."))
442     ret = GNUNET_NO;
443   GNUNET_free (ndup);
444   return ret;
445 }
446 #endif
447
448
449 /**
450  * Determine if this name is canonical (is a legal name in a zone, without delegation);
451  * note that we do not test that the name does not contain illegal characters, we only
452  * test for delegation.  Note that service records (i.e. _foo._srv) are canonical names
453  * even though they consist of multiple labels.
454  *
455  * Examples:
456  * a.b.gnu  = not canonical
457  * a         = canonical
458  * _foo._srv = canonical
459  * _f.bar    = not canonical
460  *
461  * @param name the name to test
462  * @return #GNUNET_YES if canonical
463  */
464 static int
465 is_canonical (const char *name)
466 {
467   const char *pos;
468   const char *dot;
469
470   if (NULL == strchr (name, '.'))
471     return GNUNET_YES;
472   if ('_' != name[0])
473     return GNUNET_NO;
474   pos = &name[1];
475   while (NULL != (dot = strchr (pos, '.')))
476     if ('_' != dot[1])
477       return GNUNET_NO;
478     else
479       pos = dot + 1;
480   return GNUNET_YES;
481 }
482
483 /* ************************** Resolution **************************** */
484
485 /**
486  * Exands a name ending in .+ with the zone of origin.
487  *
488  * @param rh resolution context
489  * @param name name to modify (to be free'd or returned)
490  * @return updated name
491  */
492 static char *
493 translate_dot_plus (struct GNS_ResolverHandle *rh,
494                     char *name)
495 {
496   char *ret;
497   size_t s_len = strlen (name);
498
499   if (0 != strcmp (&name[s_len - 2],
500                    ".+"))
501     return name; /* did not end in ".+" */
502   GNUNET_assert (GNUNET_YES == rh->ac_tail->gns_authority);
503   GNUNET_asprintf (&ret,
504                    "%.*s.%s",
505                    (int) (s_len - 2),
506                    name,
507                    GNUNET_NAMESTORE_pkey_to_zkey (&rh->ac_tail->authority_info.gns_authority));
508   GNUNET_free (name);
509   return ret;
510 }
511
512
513 /**
514  * Task scheduled to asynchronously fail a resolution.
515  *
516  * @param cls the 'struct GNS_ResolverHandle' of the resolution to fail
517  * @param tc task context
518  */
519 static void
520 fail_resolution (void *cls,
521                  const struct GNUNET_SCHEDULER_TaskContext *tc)
522 {
523   struct GNS_ResolverHandle *rh = cls;
524
525   rh->task_id = GNUNET_SCHEDULER_NO_TASK;
526   rh->proc (rh->proc_cls, 0, NULL);
527   GNS_resolver_lookup_cancel (rh);
528 }
529
530
531 #if (defined WINDOWS) || (defined DARWIN)
532 /* Don't have this on W32, here's a naive implementation
533  * Was somehow removed on OS X ...  */
534 void *
535 memrchr (const void *s,
536          int c,
537          size_t n)
538 {
539   const unsigned char *ucs = s;
540   ssize_t i;
541
542   for (i = n - 1; i >= 0; i--)
543     if (c == (int) ucs[i])
544       return (void *) &ucs[i];
545   return NULL;
546 }
547 #endif
548
549
550 /**
551  * Get the next, rightmost label from the name that we are trying to resolve,
552  * and update the resolution position accordingly.
553  *
554  * @param rh handle to the resolution operation to get the next label from
555  * @return NULL if there are no more labels
556  */
557 static char *
558 resolver_lookup_get_next_label (struct GNS_ResolverHandle *rh)
559 {
560   const char *rp;
561   const char *dot;
562   size_t len;
563
564   if (0 == rh->name_resolution_pos)
565     return NULL;
566   dot = memrchr (rh->name, (int) '.', rh->name_resolution_pos);
567   if (NULL == dot)
568   {
569     /* done, this was the last one */
570     len = rh->name_resolution_pos;
571     rp = rh->name;
572     rh->name_resolution_pos = 0;
573   }
574   else
575   {
576     /* advance by one label */
577     len = rh->name_resolution_pos - (dot - rh->name) - 1;
578     rp = dot + 1;
579     rh->name_resolution_pos = dot - rh->name;
580   }
581   return GNUNET_strndup (rp, len);
582 }
583
584
585 /**
586  * Gives the cummulative result obtained to the callback and clean up the request.
587  *
588  * @param rh resolution process that has culminated in a result
589  */
590 static void
591 transmit_lookup_dns_result (struct GNS_ResolverHandle *rh)
592 {
593   struct DnsResult *pos;
594   unsigned int n;
595   unsigned int i;
596
597   n = 0;
598   for (pos = rh->dns_result_head; NULL != pos; pos = pos->next)
599     n++;
600   {
601     struct GNUNET_NAMESTORE_RecordData rd[n];
602
603     i = 0;
604     for (pos = rh->dns_result_head; NULL != pos; pos = pos->next)
605     {
606       rd[i].data = pos->data;
607       rd[i].data_size = pos->data_size;
608       rd[i].record_type = pos->record_type;
609       if (0 == pos->expiration_time)
610       {
611         rd[i].flags = GNUNET_NAMESTORE_RF_RELATIVE_EXPIRATION;
612         rd[i].expiration_time = 0;
613       }
614       else
615       {
616         rd[i].flags = GNUNET_NAMESTORE_RF_NONE;
617         rd[i].expiration_time = pos->expiration_time;
618       }
619       i++;
620     }
621     GNUNET_assert (i == n);
622     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
623                 "Transmitting standard DNS result with %u records\n",
624                 n);
625     rh->proc (rh->proc_cls,
626               n,
627               rd);
628   }
629   GNS_resolver_lookup_cancel (rh);
630 }
631
632
633 /**
634  * Add a result from DNS to the records to be returned to the application.
635  *
636  * @param rh resolution request to extend with a result
637  * @param expiration_time expiration time for the answer
638  * @param record_type DNS record type of the answer
639  * @param data_size number of bytes in @a data
640  * @param data binary data to return in DNS record
641  */
642 static void
643 add_dns_result (struct GNS_ResolverHandle *rh,
644                 uint64_t expiration_time,
645                 uint32_t record_type,
646                 size_t data_size,
647                 const void *data)
648 {
649   struct DnsResult *res;
650
651   res = GNUNET_malloc (sizeof (struct DnsResult) + data_size);
652   res->expiration_time = expiration_time;
653   res->data_size = data_size;
654   res->record_type = record_type;
655   res->data = &res[1];
656   memcpy (&res[1], data, data_size);
657   GNUNET_CONTAINER_DLL_insert (rh->dns_result_head,
658                                rh->dns_result_tail,
659                                res);
660 }
661
662
663 /**
664  * We had to do a DNS lookup.  Convert the result (if any) and return
665  * it.
666  *
667  * @param cls closure with the 'struct GNS_ResolverHandle'
668  * @param addr one of the addresses of the host, NULL for the last address
669  * @param addrlen length of the address
670  */
671 static void
672 handle_dns_result (void *cls,
673                    const struct sockaddr *addr,
674                    socklen_t addrlen)
675 {
676   struct GNS_ResolverHandle *rh = cls;
677   const struct sockaddr_in *sa4;
678   const struct sockaddr_in6 *sa6;
679
680   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
681               "Received %u bytes of DNS IP data\n",
682               addrlen);
683   if (NULL == addr)
684   {
685     rh->std_resolve = NULL;
686     transmit_lookup_dns_result (rh);
687     return;
688   }
689   switch (addr->sa_family)
690   {
691   case AF_INET:
692     sa4 = (const struct sockaddr_in *) addr;
693     add_dns_result (rh,
694                     0 /* expiration time is unknown */,
695                     GNUNET_DNSPARSER_TYPE_A,
696                     sizeof (struct in_addr),
697                     &sa4->sin_addr);
698     break;
699   case AF_INET6:
700     sa6 = (const struct sockaddr_in6 *) addr;
701     add_dns_result (rh,
702                     0 /* expiration time is unknown */,
703                     GNUNET_DNSPARSER_TYPE_AAAA,
704                     sizeof (struct in6_addr),
705                     &sa6->sin6_addr);
706     break;
707   default:
708     GNUNET_break (0);
709     break;
710   }
711 }
712
713
714 /**
715  * Task scheduled to continue with the resolution process.
716  *
717  * @param cls the 'struct GNS_ResolverHandle' of the resolution
718  * @param tc task context
719  */
720 static void
721 recursive_resolution (void *cls,
722                       const struct GNUNET_SCHEDULER_TaskContext *tc);
723
724
725 /**
726  * Begin the resolution process from 'name', starting with
727  * the identification of the zone specified by 'name'.
728  *
729  * @param rh resolution to perform
730  */
731 static void
732 start_resolver_lookup (struct GNS_ResolverHandle *rh);
733
734
735 /**
736  * Function called with the result of a DNS resolution.
737  *
738  * @param cls the request handle of the resolution that
739  *        we were attempting to make
740  * @param rs socket that received the response
741  * @param dns dns response, never NULL
742  * @param dns_len number of bytes in @a dns
743  */
744 static void
745 dns_result_parser (void *cls,
746                    struct GNUNET_DNSSTUB_RequestSocket *rs,
747                    const struct GNUNET_TUN_DnsHeader *dns,
748                    size_t dns_len)
749 {
750   struct GNS_ResolverHandle *rh = cls;
751   struct GNUNET_DNSPARSER_Packet *p;
752   const struct GNUNET_DNSPARSER_Record *rec;
753   unsigned int rd_count;
754   unsigned int i;
755
756   rh->dns_request = NULL;
757   GNUNET_SCHEDULER_cancel (rh->task_id);
758   rh->task_id = GNUNET_SCHEDULER_NO_TASK;
759   p = GNUNET_DNSPARSER_parse ((const char *) dns,
760                               dns_len);
761   if (NULL == p)
762   {
763     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
764                 _("Failed to parse DNS response\n"));
765     rh->proc (rh->proc_cls, 0, NULL);
766     GNS_resolver_lookup_cancel (rh);
767     return;
768   }
769   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
770               "Received DNS response for `%s' with %u answers\n",
771               rh->ac_tail->label,
772               (unsigned int) p->num_answers);
773   if ( (p->num_answers > 0) &&
774        (GNUNET_DNSPARSER_TYPE_CNAME == p->answers[0].type) &&
775        (GNUNET_DNSPARSER_TYPE_CNAME != rh->record_type) )
776     {
777       GNUNET_free (rh->name);
778       rh->name = GNUNET_strdup (p->answers[0].data.hostname);
779       start_resolver_lookup (rh);
780       GNUNET_DNSPARSER_free_packet (p);
781       return;
782     }
783   /* FIXME: add DNAME support */
784
785   /* convert from (parsed) DNS to (binary) GNS format! */
786   rd_count = p->num_answers + p->num_authority_records + p->num_additional_records;
787   {
788     struct GNUNET_NAMESTORE_RecordData rd[rd_count];
789     unsigned int skip;
790     char buf[UINT16_MAX];
791     size_t buf_off;
792     size_t buf_start;
793
794     buf_off = 0;
795     skip = 0;
796     memset (rd, 0, sizeof (rd));
797     for (i=0;i<rd_count;i++)
798     {
799       if (i < p->num_answers)
800         rec = &p->answers[i];
801       else if (i < p->num_answers + p->num_authority_records)
802         rec = &p->authority_records[i - p->num_answers];
803       else
804         rec = &p->authority_records[i - p->num_answers - p->num_authority_records];
805       /* As we copied the full DNS name to 'rh->ac_tail->label', this
806          should be the correct check to see if this record is actually
807          a record for our label... */
808       if (0 != strcmp (rec->name,
809                        rh->ac_tail->label))
810       {
811         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
812                     "Dropping record `%s', does not match desired name `%s'\n",
813                     rec->name,
814                     rh->ac_tail->label);
815         skip++;
816         continue;
817       }
818       rd[i - skip].record_type = rec->type;
819       rd[i - skip].expiration_time = rec->expiration_time.abs_value_us;
820       switch (rec->type)
821       {
822       case GNUNET_DNSPARSER_TYPE_A:
823         if (rec->data.raw.data_len != sizeof (struct in_addr))
824         {
825           GNUNET_break_op (0);
826           skip++;
827           continue;
828         }
829         rd[i - skip].data_size = rec->data.raw.data_len;
830         rd[i - skip].data = rec->data.raw.data;
831         break;
832       case GNUNET_DNSPARSER_TYPE_AAAA:
833         if (rec->data.raw.data_len != sizeof (struct in6_addr))
834         {
835           GNUNET_break_op (0);
836           skip++;
837           continue;
838         }
839         rd[i - skip].data_size = rec->data.raw.data_len;
840         rd[i - skip].data = rec->data.raw.data;
841         break;
842       case GNUNET_DNSPARSER_TYPE_CNAME:
843       case GNUNET_DNSPARSER_TYPE_PTR:
844       case GNUNET_DNSPARSER_TYPE_NS:
845         buf_start = buf_off;
846         if (GNUNET_OK !=
847             GNUNET_DNSPARSER_builder_add_name (buf,
848                                                sizeof (buf),
849                                                &buf_off,
850                                                rec->data.hostname))
851         {
852           GNUNET_break (0);
853           skip++;
854           continue;
855         }
856         rd[i - skip].data_size = buf_off - buf_start;
857         rd[i - skip].data = &buf[buf_start];
858         break;
859       case GNUNET_DNSPARSER_TYPE_SOA:
860         buf_start = buf_off;
861         if (GNUNET_OK !=
862             GNUNET_DNSPARSER_builder_add_soa (buf,
863                                                sizeof (buf),
864                                                &buf_off,
865                                                rec->data.soa))
866         {
867           GNUNET_break (0);
868           skip++;
869           continue;
870         }
871         rd[i - skip].data_size = buf_off - buf_start;
872         rd[i - skip].data = &buf[buf_start];
873         break;
874       case GNUNET_DNSPARSER_TYPE_MX:
875         buf_start = buf_off;
876         if (GNUNET_OK !=
877             GNUNET_DNSPARSER_builder_add_mx (buf,
878                                              sizeof (buf),
879                                              &buf_off,
880                                              rec->data.mx))
881         {
882           GNUNET_break (0);
883           skip++;
884           continue;
885         }
886         rd[i - skip].data_size = buf_off - buf_start;
887         rd[i - skip].data = &buf[buf_start];
888         break;
889       case GNUNET_DNSPARSER_TYPE_SRV:
890         buf_start = buf_off;
891         if (GNUNET_OK !=
892             GNUNET_DNSPARSER_builder_add_srv (buf,
893                                               sizeof (buf),
894                                               &buf_off,
895                                               rec->data.srv))
896         {
897           GNUNET_break (0);
898           skip++;
899           continue;
900         }
901         rd[i - skip].data_size = buf_off - buf_start;
902         rd[i - skip].data = &buf[buf_start];
903         break;
904       default:
905         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
906                     _("Skipping record of unsupported type %d\n"),
907                     rec->type);
908         skip++;
909         continue;
910       }
911     }
912     rh->proc (rh->proc_cls, rd_count - skip, rd);
913     GNS_resolver_lookup_cancel (rh);
914   }
915   GNUNET_DNSPARSER_free_packet (p);
916 }
917
918
919 /**
920  * Perform recursive DNS resolution.  Asks the given DNS resolver to
921  * resolve "rh->dns_name", possibly recursively proceeding following
922  * NS delegations, CNAMES, etc., until 'rh->loop_limiter' bounds us or
923  * we find the answer.
924  *
925  * @param rh resolution information
926  */
927 static void
928 recursive_dns_resolution (struct GNS_ResolverHandle *rh)
929 {
930   struct AuthorityChain *ac;
931   socklen_t sa_len;
932   struct GNUNET_DNSPARSER_Query *query;
933   struct GNUNET_DNSPARSER_Packet *p;
934   char *dns_request;
935   size_t dns_request_length;
936
937   ac = rh->ac_tail;
938   GNUNET_assert (NULL != ac);
939   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
940               "Starting DNS lookup for `%s'\n",
941               ac->label);
942   GNUNET_assert (GNUNET_NO == ac->gns_authority);
943   switch (((const struct sockaddr *) &ac->authority_info.dns_authority.dns_ip)->sa_family)
944   {
945   case AF_INET:
946     sa_len = sizeof (struct sockaddr_in);
947     break;
948   case AF_INET6:
949     sa_len = sizeof (struct sockaddr_in6);
950     break;
951   default:
952     GNUNET_break (0);
953     rh->proc (rh->proc_cls, 0, NULL);
954     GNS_resolver_lookup_cancel (rh);
955     return;
956   }
957   query = GNUNET_new (struct GNUNET_DNSPARSER_Query);
958   query->name = GNUNET_strdup (ac->label);
959   query->type = rh->record_type;
960   query->dns_traffic_class = GNUNET_TUN_DNS_CLASS_INTERNET;
961   p = GNUNET_new (struct GNUNET_DNSPARSER_Packet);
962   p->queries = query;
963   p->num_queries = 1;
964   p->id = (uint16_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
965                                                UINT16_MAX);
966   p->flags.opcode = GNUNET_TUN_DNS_OPCODE_QUERY;
967   p->flags.recursion_desired = 1;
968   if (GNUNET_OK !=
969       GNUNET_DNSPARSER_pack (p, 1024, &dns_request, &dns_request_length))
970   {
971     GNUNET_break (0);
972     rh->proc (rh->proc_cls, 0, NULL);
973     GNS_resolver_lookup_cancel (rh);
974   }
975   else
976   {
977     rh->dns_request = GNUNET_DNSSTUB_resolve (dns_handle,
978                                               (const struct sockaddr *) &ac->authority_info.dns_authority.dns_ip,
979                                               sa_len,
980                                               dns_request,
981                                               dns_request_length,
982                                               &dns_result_parser,
983                                               rh);
984     rh->task_id = GNUNET_SCHEDULER_add_delayed (DNS_LOOKUP_TIMEOUT,
985                                                 &fail_resolution,
986                                                 rh);
987   }
988   GNUNET_free (dns_request);
989   GNUNET_DNSPARSER_free_packet (p);
990 }
991
992
993 /**
994  * We encountered a CNAME record during our resolution.
995  * Merge it into our chain.
996  *
997  * @param rh resolution we are performing
998  * @param cname value of the cname record we got for the current
999  *        authority chain tail
1000  */
1001 static void
1002 handle_gns_cname_result (struct GNS_ResolverHandle *rh,
1003                          const char *cname)
1004 {
1005   size_t nlen;
1006   char *res;
1007   struct AuthorityChain *ac;
1008
1009   nlen = strlen (cname);
1010   if ( (nlen > 2) &&
1011        (0 == strcmp (".+",
1012                      &cname[nlen - 2])) )
1013   {
1014     /* CNAME resolution continues relative to current domain */
1015     if (0 == rh->name_resolution_pos)
1016     {
1017       res = GNUNET_strndup (cname, nlen - 2);
1018       rh->name_resolution_pos = nlen - 2;
1019     }
1020     else
1021     {
1022       GNUNET_asprintf (&res,
1023                        "%.*s.%.*s",
1024                        (int) rh->name_resolution_pos,
1025                        rh->name,
1026                        (int) (nlen - 2),
1027                        cname);
1028       rh->name_resolution_pos = strlen (res);
1029     }
1030     GNUNET_free (rh->name);
1031     rh->name = res;
1032     ac = GNUNET_new (struct AuthorityChain);
1033     ac->rh = rh;
1034     ac->gns_authority = GNUNET_YES;
1035     ac->authority_info.gns_authority = rh->ac_tail->authority_info.gns_authority;
1036     ac->label = resolver_lookup_get_next_label (rh);
1037     /* tigger shortening */
1038     if (NULL != rh->shorten_key)
1039       GNS_shorten_start (rh->ac_tail->label,
1040                          &ac->authority_info.gns_authority,
1041                          rh->shorten_key);
1042     /* add AC to tail */
1043     GNUNET_CONTAINER_DLL_insert_tail (rh->ac_head,
1044                                       rh->ac_tail,
1045                                       ac);
1046     rh->task_id = GNUNET_SCHEDULER_add_now (&recursive_resolution,
1047                                             rh);
1048     return;
1049   }
1050   /* name is absolute, start from the beginning */
1051   GNUNET_free (rh->name);
1052   rh->name = GNUNET_strdup (cname);
1053   start_resolver_lookup (rh);
1054 }
1055
1056
1057 /**
1058  * Process a records that were decrypted from a block.
1059  *
1060  * @param cls closure with the 'struct GNS_ResolverHandle'
1061  * @param rd_count number of entries in @a rd array
1062  * @param rd array of records with data to store
1063  */
1064 static void
1065 handle_gns_resolution_result (void *cls,
1066                               unsigned int rd_count,
1067                               const struct GNUNET_NAMESTORE_RecordData *rd);
1068
1069
1070 /**
1071  * Callback invoked from the VPN service once a redirection is
1072  * available.  Provides the IP address that can now be used to
1073  * reach the requested destination.  Replaces the "VPN" record
1074  * with the respective A/AAAA record and continues processing.
1075  *
1076  * @param cls closure
1077  * @param af address family, AF_INET or AF_INET6; AF_UNSPEC on error;
1078  *                will match 'result_af' from the request
1079  * @param address IP address (struct in_addr or struct in_addr6, depending on 'af')
1080  *                that the VPN allocated for the redirection;
1081  *                traffic to this IP will now be redirected to the
1082  *                specified target peer; NULL on error
1083  */
1084 static void
1085 vpn_allocation_cb (void *cls,
1086                    int af,
1087                    const void *address)
1088 {
1089   struct VpnContext *vpn_ctx = cls;
1090   struct GNS_ResolverHandle *rh = vpn_ctx->rh;
1091   struct GNUNET_NAMESTORE_RecordData rd[vpn_ctx->rd_count];
1092   unsigned int i;
1093
1094   vpn_ctx->vpn_request = NULL;
1095   rh->vpn_ctx = NULL;
1096   GNUNET_assert (GNUNET_OK ==
1097                  GNUNET_NAMESTORE_records_deserialize (vpn_ctx->rd_data_size,
1098                                                        vpn_ctx->rd_data,
1099                                                        vpn_ctx->rd_count,
1100                                                        rd));
1101   for (i=0;i<vpn_ctx->rd_count;i++)
1102   {
1103     if (GNUNET_NAMESTORE_TYPE_VPN == rd[i].record_type)
1104     {
1105       switch (af)
1106       {
1107       case AF_INET:
1108         rd[i].record_type = GNUNET_DNSPARSER_TYPE_A;
1109         rd[i].data_size = sizeof (struct in_addr);
1110         rd[i].expiration_time = GNUNET_TIME_relative_to_absolute (VPN_TIMEOUT).abs_value_us;
1111         rd[i].flags = 0;
1112         rd[i].data = address;
1113         break;
1114       case AF_INET6:
1115         rd[i].record_type = GNUNET_DNSPARSER_TYPE_AAAA;
1116         rd[i].expiration_time = GNUNET_TIME_relative_to_absolute (VPN_TIMEOUT).abs_value_us;
1117         rd[i].flags = 0;
1118         rd[i].data = address;
1119         rd[i].data_size = sizeof (struct in6_addr);
1120         break;
1121       default:
1122         GNUNET_assert (0);
1123       }
1124       break;
1125     }
1126   }
1127   GNUNET_assert (i < vpn_ctx->rd_count);
1128   handle_gns_resolution_result (rh,
1129                                 vpn_ctx->rd_count,
1130                                 rd);
1131   GNUNET_free (vpn_ctx->rd_data);
1132   GNUNET_free (vpn_ctx);
1133 }
1134
1135
1136 /**
1137  * Process a records that were decrypted from a block.
1138  *
1139  * @param cls closure with the `struct GNS_ResolverHandle`
1140  * @param rd_count number of entries in @a rd array
1141  * @param rd array of records with data to store
1142  */
1143 static void
1144 handle_gns_resolution_result (void *cls,
1145                               unsigned int rd_count,
1146                               const struct GNUNET_NAMESTORE_RecordData *rd)
1147 {
1148   struct GNS_ResolverHandle *rh = cls;
1149   struct AuthorityChain *ac;
1150   unsigned int i;
1151   unsigned int j;
1152   struct sockaddr *sa;
1153   struct sockaddr_in v4;
1154   struct sockaddr_in6 v6;
1155   size_t sa_len;
1156   char *cname;
1157   struct VpnContext *vpn_ctx;
1158   const struct GNUNET_TUN_GnsVpnRecord *vpn;
1159   const char *vname;
1160   struct GNUNET_HashCode vhash;
1161   int af;
1162   char scratch[UINT16_MAX];
1163   size_t scratch_off;
1164   size_t scratch_start;
1165   size_t off;
1166   struct GNUNET_NAMESTORE_RecordData rd_new[rd_count];
1167   unsigned int rd_off;
1168
1169   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1170               "Resolution succeeded for `%s' in zone %s, got %u records\n",
1171               rh->ac_tail->label,
1172               GNUNET_NAMESTORE_z2s (&rh->ac_tail->authority_info.gns_authority),
1173               rd_count);
1174   if (0 == rh->name_resolution_pos)
1175   {
1176     /* top-level match, are we done yet? */
1177     if ( (rd_count > 0) &&
1178          (GNUNET_DNSPARSER_TYPE_CNAME == rd[0].record_type) &&
1179          (GNUNET_DNSPARSER_TYPE_CNAME != rh->record_type) )
1180     {
1181       off = 0;
1182       cname = GNUNET_DNSPARSER_parse_name (rd[0].data,
1183                                            rd[0].data_size,
1184                                            &off);
1185       if ( (NULL == cname) ||
1186            (off != rd[0].data_size) )
1187       {
1188         GNUNET_break_op (0);
1189         rh->proc (rh->proc_cls, 0, NULL);
1190         GNS_resolver_lookup_cancel (rh);
1191         return;
1192       }
1193       handle_gns_cname_result (rh,
1194                                cname);
1195       GNUNET_free (cname);
1196       return;
1197     }
1198     /* If A/AAAA was requested, but we got a VPN
1199        record, we convert it to A/AAAA using GNUnet VPN */
1200     if ( (GNUNET_DNSPARSER_TYPE_A == rh->record_type) ||
1201          (GNUNET_DNSPARSER_TYPE_AAAA == rh->record_type) )
1202     {
1203       for (i=0;i<rd_count;i++)
1204       {
1205         switch (rd[i].record_type)
1206         {
1207         case GNUNET_NAMESTORE_TYPE_VPN:
1208           {
1209             af = (GNUNET_DNSPARSER_TYPE_A == rh->record_type) ? AF_INET : AF_INET6;
1210             if (sizeof (struct GNUNET_TUN_GnsVpnRecord) <
1211                 rd[i].data_size)
1212             {
1213               GNUNET_break_op (0);
1214               rh->proc (rh->proc_cls, 0, NULL);
1215               GNS_resolver_lookup_cancel (rh);
1216               return;
1217             }
1218             vpn = (const struct GNUNET_TUN_GnsVpnRecord *) rd[i].data;
1219             vname = (const char *) &vpn[1];
1220             if ('\0' != vname[rd[i].data_size - 1 - sizeof (struct GNUNET_TUN_GnsVpnRecord)])
1221             {
1222               GNUNET_break_op (0);
1223               rh->proc (rh->proc_cls, 0, NULL);
1224               GNS_resolver_lookup_cancel (rh);
1225               return;
1226             }
1227             GNUNET_CRYPTO_hash (vname,
1228                                 strlen (vname), // FIXME: +1?
1229                                 &vhash);
1230             vpn_ctx = GNUNET_new (struct VpnContext);
1231             rh->vpn_ctx = vpn_ctx;
1232             vpn_ctx->rh = rh;
1233             vpn_ctx->rd_data_size = GNUNET_NAMESTORE_records_get_size (rd_count,
1234                                                                        rd);
1235             vpn_ctx->rd_data = GNUNET_malloc (vpn_ctx->rd_data_size);
1236             (void) GNUNET_NAMESTORE_records_serialize (rd_count,
1237                                                        rd,
1238                                                        vpn_ctx->rd_data_size,
1239                                                        vpn_ctx->rd_data);
1240             vpn_ctx->vpn_request = GNUNET_VPN_redirect_to_peer (vpn_handle,
1241                                                                 af,
1242                                                                 ntohs (vpn->proto),
1243                                                                 &vpn->peer,
1244                                                                 &vhash,
1245                                                                 GNUNET_TIME_relative_to_absolute (VPN_TIMEOUT),
1246                                                                 &vpn_allocation_cb,
1247                                                                 rh);
1248             return;
1249           }
1250         case GNUNET_NAMESTORE_TYPE_GNS2DNS:
1251           {
1252             /* delegation to DNS */
1253             goto do_recurse;
1254           }
1255         default:
1256           break;
1257         }
1258       }
1259     }
1260     /* convert relative names in record values to absolute names,
1261        using 'scratch' array for memory allocations */
1262     scratch_off = 0;
1263     rd_off = 0;
1264     for (i=0;i<rd_count;i++)
1265     {
1266       rd_new[rd_off] = rd[i];
1267       /* Check if the embedded name(s) end in "+", and if so,
1268          replace the "+" with the zone at "ac_tail", changing the name
1269          to a ".zkey".  The name is allocated on the 'scratch' array,
1270          so we can free it afterwards. */
1271       switch (rd[i].record_type)
1272       {
1273       case GNUNET_DNSPARSER_TYPE_CNAME:
1274         {
1275           char *cname;
1276
1277           off = 0;
1278           cname = GNUNET_DNSPARSER_parse_name (rd[i].data,
1279                                                rd[i].data_size,
1280                                                &off);
1281           if ( (NULL == cname) ||
1282                (off != rd[i].data_size) )
1283           {
1284             GNUNET_break_op (0); /* record not well-formed */
1285           }
1286           else
1287           {
1288             cname = translate_dot_plus (rh, cname);
1289             scratch_start = scratch_off;
1290             if (GNUNET_OK !=
1291                 GNUNET_DNSPARSER_builder_add_name (scratch,
1292                                                    sizeof (scratch),
1293                                                    &scratch_off,
1294                                                    cname))
1295             {
1296               GNUNET_break (0);
1297             }
1298             else
1299             {
1300               rd_new[rd_off].data = &scratch[scratch_start];
1301               rd_new[rd_off].data_size = scratch_off - scratch_start;
1302               rd_off++;
1303             }
1304           }
1305           GNUNET_free_non_null (cname);
1306         }
1307         break;
1308       case GNUNET_DNSPARSER_TYPE_SOA:
1309         {
1310           struct GNUNET_DNSPARSER_SoaRecord *soa;
1311
1312           off = 0;
1313           soa = GNUNET_DNSPARSER_parse_soa (rd[i].data,
1314                                             rd[i].data_size,
1315                                             &off);
1316           if ( (NULL == soa) ||
1317                (off != rd[i].data_size) )
1318           {
1319             GNUNET_break_op (0); /* record not well-formed */
1320           }
1321           else
1322           {
1323             soa->mname = translate_dot_plus (rh, soa->mname);
1324             soa->rname = translate_dot_plus (rh, soa->rname);
1325             scratch_start = scratch_off;
1326             if (GNUNET_OK !=
1327                 GNUNET_DNSPARSER_builder_add_soa (scratch,
1328                                                   sizeof (scratch),
1329                                                   &scratch_off,
1330                                                   soa))
1331             {
1332               GNUNET_break (0);
1333             }
1334             else
1335             {
1336               rd_new[rd_off].data = &scratch[scratch_start];
1337               rd_new[rd_off].data_size = scratch_off - scratch_start;
1338               rd_off++;
1339             }
1340           }
1341           if (NULL != soa)
1342             GNUNET_DNSPARSER_free_soa (soa);
1343         }
1344         break;
1345       case GNUNET_DNSPARSER_TYPE_MX:
1346         {
1347           struct GNUNET_DNSPARSER_MxRecord *mx;
1348
1349           off = 0;
1350           mx = GNUNET_DNSPARSER_parse_mx (rd[i].data,
1351                                           rd[i].data_size,
1352                                           &off);
1353           if ( (NULL == mx) ||
1354                (off != rd[i].data_size) )
1355           {
1356             GNUNET_break_op (0); /* record not well-formed */
1357           }
1358           else
1359           {
1360             mx->mxhost = translate_dot_plus (rh, mx->mxhost);
1361             scratch_start = scratch_off;
1362             if (GNUNET_OK !=
1363                 GNUNET_DNSPARSER_builder_add_mx (scratch,
1364                                                  sizeof (scratch),
1365                                                  &scratch_off,
1366                                                  mx))
1367             {
1368               GNUNET_break (0);
1369             }
1370             else
1371             {
1372               rd_new[rd_off].data = &scratch[scratch_start];
1373               rd_new[rd_off].data_size = scratch_off - scratch_start;
1374               rd_off++;
1375             }
1376           }
1377           if (NULL != mx)
1378             GNUNET_DNSPARSER_free_mx (mx);
1379         }
1380         break;
1381       case GNUNET_DNSPARSER_TYPE_SRV:
1382         {
1383           struct GNUNET_DNSPARSER_SrvRecord *srv;
1384
1385           off = 0;
1386           /* FIXME: passing rh->name here is is not necessarily what we want
1387              (SRV support not finished) */
1388           srv = GNUNET_DNSPARSER_parse_srv (rh->name,
1389                                             rd[i].data,
1390                                             rd[i].data_size,
1391                                             &off);
1392           if ( (NULL == srv) ||
1393                (off != rd[i].data_size) )
1394           {
1395             GNUNET_break_op (0); /* record not well-formed */
1396           }
1397           else
1398           {
1399             srv->domain_name = translate_dot_plus (rh, srv->domain_name);
1400             srv->target = translate_dot_plus (rh, srv->target);
1401             scratch_start = scratch_off;
1402             if (GNUNET_OK !=
1403                 GNUNET_DNSPARSER_builder_add_srv (scratch,
1404                                                   sizeof (scratch),
1405                                                   &scratch_off,
1406                                                   srv))
1407             {
1408               GNUNET_break (0);
1409             }
1410             else
1411             {
1412               rd_new[rd_off].data = &scratch[scratch_start];
1413               rd_new[rd_off].data_size = scratch_off - scratch_start;
1414               rd_off++;
1415             }
1416           }
1417           if (NULL != srv)
1418             GNUNET_DNSPARSER_free_srv (srv);
1419         }
1420         break;
1421       case GNUNET_NAMESTORE_TYPE_PKEY:
1422         /* tigger shortening */
1423         if (NULL != rh->shorten_key)
1424         {
1425           struct GNUNET_CRYPTO_EcdsaPublicKey pub;
1426
1427           if (rd[i].data_size != sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey))
1428           {
1429             GNUNET_break_op (0);
1430             break;
1431           }
1432           memcpy (&pub, rd[i].data, rd[i].data_size);
1433           GNS_shorten_start (rh->ac_tail->label,
1434                              &pub,
1435                              rh->shorten_key);
1436         }
1437         rd_off++;
1438         break;
1439       default:
1440         rd_off++;
1441         break;
1442       }
1443     }
1444
1445     /* yes, we are done, return result */
1446     rh->proc (rh->proc_cls, rd_off, rd_new);
1447     GNS_resolver_lookup_cancel (rh);
1448     return;
1449   }
1450  do_recurse:
1451   /* need to recurse, check if we can */
1452   for (i=0;i<rd_count;i++)
1453   {
1454     switch (rd[i].record_type)
1455     {
1456     case GNUNET_NAMESTORE_TYPE_PKEY:
1457       /* delegation to another zone */
1458       if (sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) !=
1459           rd[i].data_size)
1460       {
1461         GNUNET_break_op (0);
1462         rh->proc (rh->proc_cls, 0, NULL);
1463         GNS_resolver_lookup_cancel (rh);
1464         return;
1465       }
1466       /* expand authority chain */
1467       ac = GNUNET_new (struct AuthorityChain);
1468       ac->rh = rh;
1469       ac->gns_authority = GNUNET_YES;
1470       memcpy (&ac->authority_info.gns_authority,
1471               rd[i].data,
1472               sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey));
1473       ac->label = resolver_lookup_get_next_label (rh);
1474       /* tigger shortening */
1475       if (NULL != rh->shorten_key)
1476         GNS_shorten_start (rh->ac_tail->label,
1477                            &ac->authority_info.gns_authority,
1478                            rh->shorten_key);
1479       /* add AC to tail */
1480       GNUNET_CONTAINER_DLL_insert_tail (rh->ac_head,
1481                                         rh->ac_tail,
1482                                         ac);
1483       /* recurse */
1484       rh->task_id = GNUNET_SCHEDULER_add_now (&recursive_resolution,
1485                                               rh);
1486       return;
1487     case GNUNET_NAMESTORE_TYPE_GNS2DNS:
1488       {
1489         char *ns;
1490         /* resolution continues within DNS */
1491         if (GNUNET_DNSPARSER_MAX_NAME_LENGTH < rd[i].data_size)
1492         {
1493           GNUNET_break_op (0);
1494           rh->proc (rh->proc_cls, 0, NULL);
1495           GNS_resolver_lookup_cancel (rh);
1496           return;
1497         }
1498         /* find associated A/AAAA record */
1499         sa = NULL;
1500         sa_len = 0;
1501         for (j=0;j<rd_count;j++)
1502         {
1503           switch (rd[j].record_type)
1504             {
1505             case GNUNET_DNSPARSER_TYPE_A:
1506               if (sizeof (struct in_addr) != rd[j].data_size)
1507               {
1508                 GNUNET_break_op (0);
1509                 rh->proc (rh->proc_cls, 0, NULL);
1510                 GNS_resolver_lookup_cancel (rh);
1511                 return;
1512               }
1513               /* FIXME: might want to check if we support IPv4 here,
1514                  and otherwise skip this one and hope we find another */
1515               memset (&v4, 0, sizeof (v4));
1516               sa_len = sizeof (v4);
1517               v4.sin_family = AF_INET;
1518               v4.sin_port = htons (53);
1519 #if HAVE_SOCKADDR_IN_SIN_LEN
1520               v4.sin_len = (u_char) sa_len;
1521 #endif
1522               memcpy (&v4.sin_addr,
1523                       rd[j].data,
1524                       sizeof (struct in_addr));
1525               sa = (struct sockaddr *) &v4;
1526               break;
1527             case GNUNET_DNSPARSER_TYPE_AAAA:
1528               if (sizeof (struct in6_addr) != rd[j].data_size)
1529               {
1530                 GNUNET_break_op (0);
1531                 rh->proc (rh->proc_cls, 0, NULL);
1532                 GNS_resolver_lookup_cancel (rh);
1533                 return;
1534               }
1535               /* FIXME: might want to check if we support IPv6 here,
1536                  and otherwise skip this one and hope we find another */
1537               memset (&v6, 0, sizeof (v6));
1538               sa_len = sizeof (v6);
1539               v6.sin6_family = AF_INET6;
1540               v6.sin6_port = htons (53);
1541 #if HAVE_SOCKADDR_IN_SIN_LEN
1542               v6.sin6_len = (u_char) sa_len;
1543 #endif
1544               memcpy (&v6.sin6_addr,
1545                       rd[j].data,
1546                       sizeof (struct in6_addr));
1547               sa = (struct sockaddr *) &v6;
1548               break;
1549             default:
1550               break;
1551             }
1552           if (NULL != sa)
1553             break;
1554         }
1555         if (NULL == sa)
1556         {
1557           /* we cannot continue; NS without A/AAAA */
1558           rh->proc (rh->proc_cls, 0, NULL);
1559           GNS_resolver_lookup_cancel (rh);
1560           return;
1561         }
1562         /* expand authority chain */
1563         ac = GNUNET_new (struct AuthorityChain);
1564         ac->rh = rh;
1565         off = 0;
1566         ns = GNUNET_DNSPARSER_parse_name (rd[i].data,
1567                                           rd[i].data_size,
1568                                           &off);
1569         if ( (NULL == ns) ||
1570              (off != rd[i].data_size) )
1571         {
1572           GNUNET_break_op (0); /* record not well-formed */
1573           rh->proc (rh->proc_cls, 0, NULL);
1574           GNS_resolver_lookup_cancel (rh);
1575           GNUNET_free_non_null (ns);
1576           GNUNET_free (ac);
1577           return;
1578         }
1579         strcpy (ac->authority_info.dns_authority.name,
1580                 ns);
1581         memcpy (&ac->authority_info.dns_authority.dns_ip,
1582                 sa,
1583                 sa_len);
1584         /* for DNS recursion, the label is the full DNS name,
1585            created from the remainder of the GNS name and the
1586            name in the NS record */
1587         GNUNET_asprintf (&ac->label,
1588                          "%.*s%s%s",
1589                          (int) rh->name_resolution_pos,
1590                          rh->name,
1591                          (0 != rh->name_resolution_pos) ? "." : "",
1592                          ns);
1593         GNUNET_free (ns);
1594         GNUNET_CONTAINER_DLL_insert_tail (rh->ac_head,
1595                                           rh->ac_tail,
1596                                           ac);
1597         if (strlen (ac->label) > GNUNET_DNSPARSER_MAX_NAME_LENGTH)
1598         {
1599           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1600                       _("GNS lookup resulted in DNS name that is too long (`%s')\n"),
1601                       ac->label);
1602           rh->proc (rh->proc_cls, 0, NULL);
1603           GNS_resolver_lookup_cancel (rh);
1604           return;
1605         }
1606         /* recurse */
1607         rh->task_id = GNUNET_SCHEDULER_add_now (&recursive_resolution,
1608                                                 rh);
1609         return;
1610       }
1611     case GNUNET_DNSPARSER_TYPE_CNAME:
1612       {
1613         char *cname;
1614
1615         off = 0;
1616         cname = GNUNET_DNSPARSER_parse_name (rd[i].data,
1617                                              rd[i].data_size,
1618                                              &off);
1619         if ( (NULL == cname) ||
1620              (off != rd[i].data_size) )
1621         {
1622           GNUNET_break_op (0); /* record not well-formed */
1623           rh->proc (rh->proc_cls, 0, NULL);
1624           GNS_resolver_lookup_cancel (rh);
1625           GNUNET_free_non_null (cname);
1626           return;
1627         }
1628         handle_gns_cname_result (rh,
1629                                  cname);
1630         GNUNET_free (cname);
1631         return;
1632       }
1633       /* FIXME: handle DNAME */
1634     default:
1635       /* skip */
1636       break;
1637     }
1638   }
1639   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1640               _("GNS lookup recursion failed (no delegation record found)\n"));
1641   rh->proc (rh->proc_cls, 0, NULL);
1642   GNS_resolver_lookup_cancel (rh);
1643 }
1644
1645
1646 /**
1647  * Function called once the namestore has completed the request for
1648  * caching a block.
1649  *
1650  * @param cls closure with the `struct CacheOps`
1651  * @param success #GNUNET_OK on success
1652  * @param emsg error message
1653  */
1654 static void
1655 namestore_cache_continuation (void *cls,
1656                               int32_t success,
1657                               const char *emsg)
1658 {
1659   struct CacheOps *co = cls;
1660
1661   co->namestore_qe_cache = NULL;
1662   if (NULL != emsg)
1663     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1664                 _("Failed to cache GNS resolution: %s\n"),
1665                 emsg);
1666   GNUNET_CONTAINER_DLL_remove (co_head,
1667                                co_tail,
1668                                co);
1669   GNUNET_free (co);
1670 }
1671
1672
1673 /**
1674  * Iterator called on each result obtained for a DHT
1675  * operation that expects a reply
1676  *
1677  * @param cls closure with the `struct GNS_ResolverHandle`
1678  * @param exp when will this value expire
1679  * @param key key of the result
1680  * @param get_path peers on reply path (or NULL if not recorded)
1681  *                 [0] = datastore's first neighbor, [length - 1] = local peer
1682  * @param get_path_length number of entries in @a get_path
1683  * @param put_path peers on the PUT path (or NULL if not recorded)
1684  *                 [0] = origin, [length - 1] = datastore
1685  * @param put_path_length number of entries in @a put_path
1686  * @param type type of the result
1687  * @param size number of bytes in data
1688  * @param data pointer to the result data
1689  */
1690 static void
1691 handle_dht_response (void *cls,
1692                      struct GNUNET_TIME_Absolute exp,
1693                      const struct GNUNET_HashCode *key,
1694                      const struct GNUNET_PeerIdentity *get_path,
1695                      unsigned int get_path_length,
1696                      const struct GNUNET_PeerIdentity *put_path,
1697                      unsigned int put_path_length,
1698                      enum GNUNET_BLOCK_Type type,
1699                      size_t size, const void *data)
1700 {
1701   struct GNS_ResolverHandle *rh = cls;
1702   struct AuthorityChain *ac = rh->ac_tail;
1703   const struct GNUNET_NAMESTORE_Block *block;
1704   struct CacheOps *co;
1705
1706   GNUNET_DHT_get_stop (rh->get_handle);
1707   rh->get_handle = NULL;
1708   GNUNET_CONTAINER_heap_remove_node (rh->dht_heap_node);
1709   rh->dht_heap_node = NULL;
1710   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1711               "Handling response from the DHT\n");
1712   if (size < sizeof (struct GNUNET_NAMESTORE_Block))
1713   {
1714     /* how did this pass DHT block validation!? */
1715     GNUNET_break (0);
1716     rh->proc (rh->proc_cls, 0, NULL);
1717     GNS_resolver_lookup_cancel (rh);
1718     return;
1719   }
1720   block = data;
1721   if (size !=
1722       ntohl (block->purpose.size) +
1723       sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) +
1724       sizeof (struct GNUNET_CRYPTO_EcdsaSignature))
1725   {
1726     /* how did this pass DHT block validation!? */
1727     GNUNET_break (0);
1728     rh->proc (rh->proc_cls, 0, NULL);
1729     GNS_resolver_lookup_cancel (rh);
1730     return;
1731   }
1732   if (GNUNET_OK !=
1733       GNUNET_NAMESTORE_block_decrypt (block,
1734                                       &ac->authority_info.gns_authority,
1735                                       ac->label,
1736                                       &handle_gns_resolution_result,
1737                                       rh))
1738   {
1739     GNUNET_break_op (0); /* block was ill-formed */
1740     rh->proc (rh->proc_cls, 0, NULL);
1741     GNS_resolver_lookup_cancel (rh);
1742     return;
1743   }
1744   /* Cache well-formed blocks */
1745   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1746               "Caching response from the DHT in namestore\n");
1747   co = GNUNET_new (struct CacheOps);
1748   co->namestore_qe_cache = GNUNET_NAMESTORE_block_cache (namestore_handle,
1749                                                          block,
1750                                                          &namestore_cache_continuation,
1751                                                          co);
1752   GNUNET_CONTAINER_DLL_insert (co_head,
1753                                co_tail,
1754                                co);
1755 }
1756
1757
1758 /**
1759  * Process a record that was stored in the namestore.
1760  *
1761  * @param cls closure with the `struct GNS_ResolverHandle`
1762  * @param block block that was stored in the namestore
1763  */
1764 static void
1765 handle_namestore_block_response (void *cls,
1766                                  const struct GNUNET_NAMESTORE_Block *block)
1767 {
1768   struct GNS_ResolverHandle *rh = cls;
1769   struct GNS_ResolverHandle *rx;
1770   struct AuthorityChain *ac = rh->ac_tail;
1771   const char *label = ac->label;
1772   const struct GNUNET_CRYPTO_EcdsaPublicKey *auth = &ac->authority_info.gns_authority;
1773   struct GNUNET_HashCode query;
1774
1775   GNUNET_NAMESTORE_query_from_public_key (auth,
1776                                           label,
1777                                           &query);
1778   GNUNET_assert (NULL != rh->namestore_qe);
1779   rh->namestore_qe = NULL;
1780   if ( (GNUNET_NO == rh->only_cached) &&
1781        ( (NULL == block) ||
1782          (0 == GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_ntoh (block->expiration_time)).rel_value_us) ) )
1783   {
1784     /* Namestore knows nothing; try DHT lookup */
1785     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1786                 "Starting DHT lookup for `%s' in zone %s\n",
1787                 ac->label,
1788                 GNUNET_NAMESTORE_z2s (&ac->authority_info.gns_authority));
1789     GNUNET_assert (NULL == rh->get_handle);
1790     rh->get_handle = GNUNET_DHT_get_start (dht_handle,
1791                                            GNUNET_BLOCK_TYPE_GNS_NAMERECORD,
1792                                            &query,
1793                                            DHT_GNS_REPLICATION_LEVEL,
1794                                            GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE,
1795                                            NULL, 0,
1796                                            &handle_dht_response, rh);
1797     rh->dht_heap_node = GNUNET_CONTAINER_heap_insert (dht_lookup_heap,
1798                                                       rh,
1799                                                       GNUNET_TIME_absolute_get ().abs_value_us);
1800     if (GNUNET_CONTAINER_heap_get_size (dht_lookup_heap) > max_allowed_background_queries)
1801     {
1802       /* fail longest-standing DHT request */
1803       rx = GNUNET_CONTAINER_heap_peek (dht_lookup_heap);
1804       GNUNET_assert (NULL != rx);
1805       rx->proc (rx->proc_cls, 0, NULL);
1806       GNS_resolver_lookup_cancel (rx);
1807     }
1808     return;
1809   }
1810   if ( (NULL == block) ||
1811        (0 == GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_ntoh (block->expiration_time)).rel_value_us) )
1812   {
1813     /* DHT not permitted and no local result, fail */
1814     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1815                 "Resolution failed for `%s' in zone %s (DHT lookup not permitted by configuration)\n",
1816                 ac->label,
1817                 GNUNET_NAMESTORE_z2s (&ac->authority_info.gns_authority));
1818     rh->proc (rh->proc_cls, 0, NULL);
1819     GNS_resolver_lookup_cancel (rh);
1820     return;
1821   }
1822   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1823               "Decrypting block from the namestore\n");
1824   if (GNUNET_OK !=
1825       GNUNET_NAMESTORE_block_decrypt (block,
1826                                       auth,
1827                                       label,
1828                                       &handle_gns_resolution_result,
1829                                       rh))
1830   {
1831     GNUNET_break_op (0); /* block was ill-formed */
1832     rh->proc (rh->proc_cls, 0, NULL);
1833     GNS_resolver_lookup_cancel (rh);
1834     return;
1835   }
1836 }
1837
1838
1839 /**
1840  * Lookup tail of our authority chain in the namestore.
1841  *
1842  * @param rh query we are processing
1843  */
1844 static void
1845 recursive_gns_resolution_namestore (struct GNS_ResolverHandle *rh)
1846 {
1847   struct AuthorityChain *ac = rh->ac_tail;
1848   struct GNUNET_HashCode query;
1849
1850   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1851               "Starting GNS resolution for `%s' in zone %s\n",
1852               ac->label,
1853               GNUNET_NAMESTORE_z2s (&ac->authority_info.gns_authority));
1854   GNUNET_NAMESTORE_query_from_public_key (&ac->authority_info.gns_authority,
1855                                           ac->label,
1856                                           &query);
1857   rh->namestore_qe = GNUNET_NAMESTORE_lookup_block (namestore_handle,
1858                                                     &query,
1859                                                     &handle_namestore_block_response,
1860                                                     rh);
1861   GNUNET_assert (NULL != rh->namestore_qe);
1862 }
1863
1864
1865 /**
1866  * Task scheduled to continue with the resolution process.
1867  *
1868  * @param cls the `struct GNS_ResolverHandle` of the resolution
1869  * @param tc task context
1870  */
1871 static void
1872 recursive_resolution (void *cls,
1873                       const struct GNUNET_SCHEDULER_TaskContext *tc)
1874 {
1875   struct GNS_ResolverHandle *rh = cls;
1876
1877   rh->task_id = GNUNET_SCHEDULER_NO_TASK;
1878   if (MAX_RECURSION < rh->loop_limiter++)
1879   {
1880     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1881                 "Encountered unbounded recursion resolving `%s'\n",
1882                 rh->name);
1883     rh->proc (rh->proc_cls, 0, NULL);
1884     GNS_resolver_lookup_cancel (rh);
1885     return;
1886   }
1887   if (GNUNET_YES == rh->ac_tail->gns_authority)
1888     recursive_gns_resolution_namestore (rh);
1889   else
1890     recursive_dns_resolution (rh);
1891 }
1892
1893
1894 /**
1895  * Begin the resolution process from 'name', starting with
1896  * the identification of the zone specified by 'name'.
1897  *
1898  * @param rh resolution to perform
1899  */
1900 static void
1901 start_resolver_lookup (struct GNS_ResolverHandle *rh)
1902 {
1903   struct AuthorityChain *ac;
1904   char *x;
1905   char *y;
1906   char *pkey;
1907
1908   if ( ( (GNUNET_YES == is_canonical (rh->name)) &&
1909          (0 != strcmp (GNUNET_GNS_TLD, rh->name)) ) ||
1910        ( (GNUNET_YES != is_gnu_tld (rh->name)) &&
1911          (GNUNET_YES != is_zkey_tld (rh->name)) ) )
1912   {
1913     /* use standard DNS lookup */
1914     int af;
1915
1916     switch (rh->record_type)
1917     {
1918     case GNUNET_DNSPARSER_TYPE_A:
1919       af = AF_INET;
1920       break;
1921     case GNUNET_DNSPARSER_TYPE_AAAA:
1922       af = AF_INET6;
1923       break;
1924     default:
1925       af = AF_UNSPEC;
1926       break;
1927     }
1928     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1929                 "Doing standard DNS lookup for `%s'\n",
1930                 rh->name);
1931     rh->std_resolve = GNUNET_RESOLVER_ip_get (rh->name,
1932                                               af,
1933                                               DNS_LOOKUP_TIMEOUT,
1934                                               &handle_dns_result,
1935                                               rh);
1936     return;
1937   }
1938   if (is_zkey_tld (rh->name))
1939   {
1940     /* Name ends with ".zkey", try to replace authority zone with zkey
1941        authority */
1942     GNUNET_free (resolver_lookup_get_next_label (rh)); /* will return "zkey" */
1943     x = resolver_lookup_get_next_label (rh); /* will return 'x' coordinate */
1944     y = resolver_lookup_get_next_label (rh); /* will return 'y' coordinate */
1945     GNUNET_asprintf (&pkey,
1946                      "%s%s",
1947                      x, y);
1948     if ( (NULL == x) ||
1949          (NULL == y) ||
1950          (GNUNET_OK !=
1951           GNUNET_CRYPTO_ecdsa_public_key_from_string (pkey,
1952                                                     strlen (pkey),
1953                                                     &rh->authority_zone)) )
1954     {
1955       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1956                   _("Hostname `%s' is not well-formed, resolution fails\n"),
1957                   rh->name);
1958       rh->task_id = GNUNET_SCHEDULER_add_now (&fail_resolution, rh);
1959     }
1960     GNUNET_free_non_null (x);
1961     GNUNET_free_non_null (y);
1962     GNUNET_free (pkey);
1963   }
1964   else
1965   {
1966     /* Name ends with ".gnu", eat ".gnu" and continue with resolution */
1967     GNUNET_free (resolver_lookup_get_next_label (rh));
1968   }
1969   ac = GNUNET_new (struct AuthorityChain);
1970   ac->rh = rh;
1971   ac->label = resolver_lookup_get_next_label (rh);
1972   if (NULL == ac->label)
1973     /* name was just "gnu", so we default to label '+' */
1974     ac->label = GNUNET_strdup (GNUNET_GNS_MASTERZONE_STR);
1975   ac->gns_authority = GNUNET_YES;
1976   ac->authority_info.gns_authority = rh->authority_zone;
1977   GNUNET_CONTAINER_DLL_insert_tail (rh->ac_head,
1978                                     rh->ac_tail,
1979                                     ac);
1980   rh->task_id = GNUNET_SCHEDULER_add_now (&recursive_resolution,
1981                                           rh);
1982 }
1983
1984
1985 /**
1986  * Lookup of a record in a specific zone calls lookup result processor
1987  * on result.
1988  *
1989  * @param zone the zone to perform the lookup in
1990  * @param record_type the record type to look up
1991  * @param name the name to look up
1992  * @param shorten_key a private key for use with PSEU import (can be NULL)
1993  * @param only_cached #GNUNET_NO to only check locally not DHT for performance
1994  * @param proc the processor to call on result
1995  * @param proc_cls the closure to pass to @a proc
1996  * @return handle to cancel operation
1997  */
1998 struct GNS_ResolverHandle *
1999 GNS_resolver_lookup (const struct GNUNET_CRYPTO_EcdsaPublicKey *zone,
2000                      uint32_t record_type,
2001                      const char *name,
2002                      const struct GNUNET_CRYPTO_EcdsaPrivateKey *shorten_key,
2003                      int only_cached,
2004                      GNS_ResultProcessor proc, void *proc_cls)
2005 {
2006   struct GNS_ResolverHandle *rh;
2007
2008   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2009               (NULL == shorten_key)
2010               ? "Starting lookup for `%s' with shortening disabled\n"
2011               : "Starting lookup for `%s' with shortening enabled\n",
2012               name);
2013   rh = GNUNET_new (struct GNS_ResolverHandle);
2014   GNUNET_CONTAINER_DLL_insert (rlh_head,
2015                                rlh_tail,
2016                                rh);
2017   rh->authority_zone = *zone;
2018   rh->proc = proc;
2019   rh->proc_cls = proc_cls;
2020   rh->only_cached = only_cached;
2021   rh->record_type = record_type;
2022   rh->name = GNUNET_strdup (name);
2023   rh->name_resolution_pos = strlen (name);
2024   if (NULL != shorten_key)
2025   {
2026     rh->shorten_key = GNUNET_new (struct GNUNET_CRYPTO_EcdsaPrivateKey);
2027     *rh->shorten_key = *shorten_key;
2028   }
2029   start_resolver_lookup (rh);
2030   return rh;
2031 }
2032
2033
2034 /**
2035  * Cancel active resolution (i.e. client disconnected).
2036  *
2037  * @param rh resolution to abort
2038  */
2039 void
2040 GNS_resolver_lookup_cancel (struct GNS_ResolverHandle *rh)
2041 {
2042   struct DnsResult *dr;
2043   struct AuthorityChain *ac;
2044   struct VpnContext *vpn_ctx;
2045
2046   GNUNET_CONTAINER_DLL_remove (rlh_head,
2047                                rlh_tail,
2048                                rh);
2049   while (NULL != (ac = rh->ac_head))
2050   {
2051     GNUNET_CONTAINER_DLL_remove (rh->ac_head,
2052                                  rh->ac_tail,
2053                                  ac);
2054     GNUNET_free (ac->label);
2055     GNUNET_free (ac);
2056   }
2057   if (GNUNET_SCHEDULER_NO_TASK != rh->task_id)
2058   {
2059     GNUNET_SCHEDULER_cancel (rh->task_id);
2060     rh->task_id = GNUNET_SCHEDULER_NO_TASK;
2061   }
2062   if (NULL != rh->get_handle)
2063   {
2064     GNUNET_DHT_get_stop (rh->get_handle);
2065     rh->get_handle = NULL;
2066   }
2067   if (NULL != rh->dht_heap_node)
2068   {
2069     GNUNET_CONTAINER_heap_remove_node (rh->dht_heap_node);
2070     rh->dht_heap_node = NULL;
2071   }
2072   if (NULL != (vpn_ctx = rh->vpn_ctx))
2073   {
2074     GNUNET_VPN_cancel_request (vpn_ctx->vpn_request);
2075     GNUNET_free (vpn_ctx->rd_data);
2076     GNUNET_free (vpn_ctx);
2077   }
2078   if (NULL != rh->dns_request)
2079   {
2080     GNUNET_DNSSTUB_resolve_cancel (rh->dns_request);
2081     rh->dns_request = NULL;
2082   }
2083   if (NULL != rh->namestore_qe)
2084   {
2085     GNUNET_NAMESTORE_cancel (rh->namestore_qe);
2086     rh->namestore_qe = NULL;
2087   }
2088   if (NULL != rh->std_resolve)
2089   {
2090     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2091                 "Canceling standard DNS resolution\n");
2092     GNUNET_RESOLVER_request_cancel (rh->std_resolve);
2093     rh->std_resolve = NULL;
2094   }
2095   while (NULL != (dr = rh->dns_result_head))
2096   {
2097     GNUNET_CONTAINER_DLL_remove (rh->dns_result_head,
2098                                  rh->dns_result_tail,
2099                                  dr);
2100     GNUNET_free (dr);
2101   }
2102   GNUNET_free_non_null (rh->shorten_key);
2103   GNUNET_free (rh->name);
2104   GNUNET_free (rh);
2105 }
2106
2107
2108 /* ***************** Resolver initialization ********************* */
2109
2110
2111 /**
2112  * Initialize the resolver
2113  *
2114  * @param nh the namestore handle
2115  * @param dht the dht handle
2116  * @param c configuration handle
2117  * @param max_bg_queries maximum number of parallel background queries in dht
2118  */
2119 void
2120 GNS_resolver_init (struct GNUNET_NAMESTORE_Handle *nh,
2121                    struct GNUNET_DHT_Handle *dht,
2122                    const struct GNUNET_CONFIGURATION_Handle *c,
2123                    unsigned long long max_bg_queries)
2124 {
2125   char *dns_ip;
2126
2127   cfg = c;
2128   namestore_handle = nh;
2129   dht_handle = dht;
2130   dht_lookup_heap =
2131     GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2132   max_allowed_background_queries = max_bg_queries;
2133   if (GNUNET_OK !=
2134       GNUNET_CONFIGURATION_get_value_string (c,
2135                                              "gns",
2136                                              "DNS_RESOLVER",
2137                                              &dns_ip))
2138   {
2139     /* user did not specify DNS resolver, use 8.8.8.8 */
2140     dns_ip = GNUNET_strdup ("8.8.8.8");
2141   }
2142   dns_handle = GNUNET_DNSSTUB_start (dns_ip);
2143   GNUNET_free (dns_ip);
2144   vpn_handle = GNUNET_VPN_connect (cfg);
2145 }
2146
2147
2148 /**
2149  * Shutdown resolver
2150  */
2151 void
2152 GNS_resolver_done ()
2153 {
2154   struct GNS_ResolverHandle *rh;
2155   struct CacheOps *co;
2156
2157   /* abort active resolutions */
2158   while (NULL != (rh = rlh_head))
2159   {
2160     rh->proc (rh->proc_cls, 0, NULL);
2161     GNS_resolver_lookup_cancel (rh);
2162   }
2163   while (NULL != (co = co_head))
2164   {
2165     GNUNET_CONTAINER_DLL_remove (co_head,
2166                                  co_tail,
2167                                  co);
2168     GNUNET_NAMESTORE_cancel (co->namestore_qe_cache);
2169     GNUNET_free (co);
2170   }
2171   GNUNET_CONTAINER_heap_destroy (dht_lookup_heap);
2172   dht_lookup_heap = NULL;
2173   GNUNET_DNSSTUB_stop (dns_handle);
2174   dns_handle = NULL;
2175   GNUNET_VPN_disconnect (vpn_handle);
2176   vpn_handle = NULL;
2177   dht_handle = NULL;
2178   namestore_handle = NULL;
2179 }
2180
2181
2182 /* *************** common helper functions (do not really belong here) *********** */
2183
2184 /**
2185  * Checks if @a name ends in ".TLD"
2186  *
2187  * @param name the name to check
2188  * @param tld the TLD to check for
2189  * @return GNUNET_YES or GNUNET_NO
2190  */
2191 int
2192 is_tld (const char* name, const char* tld)
2193 {
2194   size_t offset = 0;
2195
2196   if (strlen (name) <= strlen (tld))
2197     return GNUNET_NO;
2198   offset = strlen (name) - strlen (tld);
2199   if (0 != strcmp (name + offset, tld))
2200     return GNUNET_NO;
2201   return GNUNET_YES;
2202 }
2203
2204
2205 /* end of gnunet-service-gns_resolver.c */