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