xref: /freebsd/contrib/unbound/dns64/dns64.c (revision 206b73d0)
1 /*
2  * dns64/dns64.c - DNS64 module
3  *
4  * Copyright (c) 2009, Viagénie. All rights reserved.
5  *
6  * This software is open source.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * Neither the name of Viagénie nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
25  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
27  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 /**
37  * \file
38  *
39  * This file contains a module that performs DNS64 query processing.
40  */
41 
42 #include "config.h"
43 #include "dns64/dns64.h"
44 #include "services/cache/dns.h"
45 #include "services/cache/rrset.h"
46 #include "util/config_file.h"
47 #include "util/data/msgreply.h"
48 #include "util/fptr_wlist.h"
49 #include "util/net_help.h"
50 #include "util/regional.h"
51 #include "util/storage/dnstree.h"
52 #include "util/data/dname.h"
53 #include "sldns/str2wire.h"
54 
55 /******************************************************************************
56  *                                                                            *
57  *                             STATIC CONSTANTS                               *
58  *                                                                            *
59  ******************************************************************************/
60 
61 /**
62  * This is the default DNS64 prefix that is used whent he dns64 module is listed
63  * in module-config but when the dns64-prefix variable is not present.
64  */
65 static const char DEFAULT_DNS64_PREFIX[] = "64:ff9b::/96";
66 
67 /**
68  * Maximum length of a domain name in a PTR query in the .in-addr.arpa tree.
69  */
70 #define MAX_PTR_QNAME_IPV4 30
71 
72 /**
73  * State of DNS64 processing for a query.
74  */
75 enum dns64_state {
76     DNS64_INTERNAL_QUERY,    /**< Internally-generated query, no DNS64
77                                   processing. */
78     DNS64_NEW_QUERY,         /**< Query for which we're the first module in
79                                   line. */
80     DNS64_SUBQUERY_FINISHED  /**< Query for which we generated a sub-query, and
81                                   for which this sub-query is finished. */
82 };
83 
84 /**
85  * Per-query module-specific state.  For the DNS64 module.
86  */
87 struct dns64_qstate {
88 	/** State of the DNS64 module. */
89 	enum dns64_state state;
90 	/** If the dns64 module started with no_cache bool set in the qstate,
91 	 * a message to tell it to not modify the cache contents, then this
92 	 * is true.  The dns64 module is then free to modify that flag for
93 	 * its own purposes.
94 	 * Otherwise, it is false, the dns64 module was not told to no_cache */
95 	int started_no_cache_store;
96 };
97 
98 /******************************************************************************
99  *                                                                            *
100  *                                 STRUCTURES                                 *
101  *                                                                            *
102  ******************************************************************************/
103 
104 /**
105  * This structure contains module configuration information. One instance of
106  * this structure exists per instance of the module. Normally there is only one
107  * instance of the module.
108  */
109 struct dns64_env {
110     /**
111      * DNS64 prefix address. We're using a full sockaddr instead of just an
112      * in6_addr because we can reuse Unbound's generic string parsing functions.
113      * It will always contain a sockaddr_in6, and only the sin6_addr member will
114      * ever be used.
115      */
116     struct sockaddr_storage prefix_addr;
117 
118     /**
119      * This is always sizeof(sockaddr_in6).
120      */
121     socklen_t prefix_addrlen;
122 
123     /**
124      * This is the CIDR length of the prefix. It needs to be between 0 and 96.
125      */
126     int prefix_net;
127 
128     /**
129      * Tree of names for which AAAA is ignored. always synthesize from A.
130      */
131     rbtree_type ignore_aaaa;
132 };
133 
134 
135 /******************************************************************************
136  *                                                                            *
137  *                             UTILITY FUNCTIONS                              *
138  *                                                                            *
139  ******************************************************************************/
140 
141 /**
142  * Generic macro for swapping two variables.
143  *
144  * \param t Type of the variables. (e.g. int)
145  * \param a First variable.
146  * \param b Second variable.
147  *
148  * \warning Do not attempt something foolish such as swap(int,a++,b++)!
149  */
150 #define swap(t,a,b) do {t x = a; a = b; b = x;} while(0)
151 
152 /**
153  * Reverses a string.
154  *
155  * \param begin Points to the first character of the string.
156  * \param end   Points one past the last character of the string.
157  */
158 static void
159 reverse(char* begin, char* end)
160 {
161     while ( begin < --end ) {
162         swap(char, *begin, *end);
163         ++begin;
164     }
165 }
166 
167 /**
168  * Convert an unsigned integer to a string. The point of this function is that
169  * of being faster than sprintf().
170  *
171  * \param n The number to be converted.
172  * \param s The result will be written here. Must be large enough, be careful!
173  *
174  * \return The number of characters written.
175  */
176 static int
177 uitoa(unsigned n, char* s)
178 {
179     char* ss = s;
180     do {
181         *ss++ = '0' + n % 10;
182     } while (n /= 10);
183     reverse(s, ss);
184     return ss - s;
185 }
186 
187 /**
188  * Extract an IPv4 address embedded in the IPv6 address \a ipv6 at offset \a
189  * offset (in bits). Note that bits are not necessarily aligned on bytes so we
190  * need to be careful.
191  *
192  * \param ipv6   IPv6 address represented as a 128-bit array in big-endian
193  *               order.
194  * \param offset Index of the MSB of the IPv4 address embedded in the IPv6
195  *               address.
196  */
197 static uint32_t
198 extract_ipv4(const uint8_t ipv6[16], const int offset)
199 {
200     uint32_t ipv4 = (uint32_t)ipv6[offset/8+0] << (24 + (offset%8))
201                   | (uint32_t)ipv6[offset/8+1] << (16 + (offset%8))
202                   | (uint32_t)ipv6[offset/8+2] << ( 8 + (offset%8))
203                   | (uint32_t)ipv6[offset/8+3] << ( 0 + (offset%8));
204     if (offset/8+4 < 16)
205         ipv4 |= (uint32_t)ipv6[offset/8+4] >> (8 - offset%8);
206     return ipv4;
207 }
208 
209 /**
210  * Builds the PTR query name corresponding to an IPv4 address. For example,
211  * given the number 3,464,175,361, this will build the string
212  * "\03206\03123\0231\011\07in-addr\04arpa".
213  *
214  * \param ipv4 IPv4 address represented as an unsigned 32-bit number.
215  * \param ptr  The result will be written here. Must be large enough, be
216  *             careful!
217  *
218  * \return The number of characters written.
219  */
220 static size_t
221 ipv4_to_ptr(uint32_t ipv4, char ptr[MAX_PTR_QNAME_IPV4])
222 {
223     static const char IPV4_PTR_SUFFIX[] = "\07in-addr\04arpa";
224     int i;
225     char* c = ptr;
226 
227     for (i = 0; i < 4; ++i) {
228         *c = uitoa((unsigned int)(ipv4 % 256), c + 1);
229         c += *c + 1;
230         ipv4 /= 256;
231     }
232 
233     memmove(c, IPV4_PTR_SUFFIX, sizeof(IPV4_PTR_SUFFIX));
234 
235     return c + sizeof(IPV4_PTR_SUFFIX) - ptr;
236 }
237 
238 /**
239  * Converts an IPv6-related domain name string from a PTR query into an IPv6
240  * address represented as a 128-bit array.
241  *
242  * \param ptr  The domain name. (e.g. "\011[...]\010\012\016\012\03ip6\04arpa")
243  * \param ipv6 The result will be written here, in network byte order.
244  *
245  * \return 1 on success, 0 on failure.
246  */
247 static int
248 ptr_to_ipv6(const char* ptr, uint8_t ipv6[16])
249 {
250     int i;
251 
252     for (i = 0; i < 64; i++) {
253         int x;
254 
255         if (ptr[i++] != 1)
256             return 0;
257 
258         if (ptr[i] >= '0' && ptr[i] <= '9') {
259             x = ptr[i] - '0';
260         } else if (ptr[i] >= 'a' && ptr[i] <= 'f') {
261             x = ptr[i] - 'a' + 10;
262         } else if (ptr[i] >= 'A' && ptr[i] <= 'F') {
263             x = ptr[i] - 'A' + 10;
264         } else {
265             return 0;
266         }
267 
268         ipv6[15-i/4] |= x << (2 * ((i-1) % 4));
269     }
270 
271     return 1;
272 }
273 
274 /**
275  * Synthesize an IPv6 address based on an IPv4 address and the DNS64 prefix.
276  *
277  * \param prefix_addr DNS64 prefix address.
278  * \param prefix_net  CIDR length of the DNS64 prefix. Must be between 0 and 96.
279  * \param a           IPv4 address.
280  * \param aaaa        IPv6 address. The result will be written here.
281  */
282 static void
283 synthesize_aaaa(const uint8_t prefix_addr[16], int prefix_net,
284         const uint8_t a[4], uint8_t aaaa[16])
285 {
286     memcpy(aaaa, prefix_addr, 16);
287     aaaa[prefix_net/8+0] |= a[0] >> (0+prefix_net%8);
288     aaaa[prefix_net/8+1] |= a[0] << (8-prefix_net%8);
289     aaaa[prefix_net/8+1] |= a[1] >> (0+prefix_net%8);
290     aaaa[prefix_net/8+2] |= a[1] << (8-prefix_net%8);
291     aaaa[prefix_net/8+2] |= a[2] >> (0+prefix_net%8);
292     aaaa[prefix_net/8+3] |= a[2] << (8-prefix_net%8);
293     aaaa[prefix_net/8+3] |= a[3] >> (0+prefix_net%8);
294     if (prefix_net/8+4 < 16)  /* <-- my beautiful symmetry is destroyed! */
295     aaaa[prefix_net/8+4] |= a[3] << (8-prefix_net%8);
296 }
297 
298 
299 /******************************************************************************
300  *                                                                            *
301  *                           DNS64 MODULE FUNCTIONS                           *
302  *                                                                            *
303  ******************************************************************************/
304 
305 /**
306  * insert ignore_aaaa element into the tree
307  * @param dns64_env: module env.
308  * @param str: string with domain name.
309  * @return false on failure.
310  */
311 static int
312 dns64_insert_ignore_aaaa(struct dns64_env* dns64_env, char* str)
313 {
314 	/* parse and insert element */
315 	struct name_tree_node* node;
316 	node = (struct name_tree_node*)calloc(1, sizeof(*node));
317 	if(!node) {
318 		log_err("out of memory");
319 		return 0;
320 	}
321 	node->name = sldns_str2wire_dname(str, &node->len);
322 	if(!node->name) {
323 		free(node);
324 		log_err("cannot parse dns64-ignore-aaaa: %s", str);
325 		return 0;
326 	}
327 	node->labs = dname_count_labels(node->name);
328 	node->dclass = LDNS_RR_CLASS_IN;
329 	if(!name_tree_insert(&dns64_env->ignore_aaaa, node,
330 		node->name, node->len, node->labs, node->dclass)) {
331 		/* ignore duplicate element */
332 		free(node->name);
333 		free(node);
334 		return 1;
335 	}
336 	return 1;
337 }
338 
339 /**
340  * This function applies the configuration found in the parsed configuration
341  * file \a cfg to this instance of the dns64 module. Currently only the DNS64
342  * prefix (a.k.a. Pref64) is configurable.
343  *
344  * \param dns64_env Module-specific global parameters.
345  * \param cfg       Parsed configuration file.
346  */
347 static int
348 dns64_apply_cfg(struct dns64_env* dns64_env, struct config_file* cfg)
349 {
350     struct config_strlist* s;
351     verbose(VERB_ALGO, "dns64-prefix: %s", cfg->dns64_prefix);
352     if (!netblockstrtoaddr(cfg->dns64_prefix ? cfg->dns64_prefix :
353                 DEFAULT_DNS64_PREFIX, 0, &dns64_env->prefix_addr,
354                 &dns64_env->prefix_addrlen, &dns64_env->prefix_net)) {
355         log_err("cannot parse dns64-prefix netblock: %s", cfg->dns64_prefix);
356         return 0;
357     }
358     if (!addr_is_ip6(&dns64_env->prefix_addr, dns64_env->prefix_addrlen)) {
359         log_err("dns64_prefix is not IPv6: %s", cfg->dns64_prefix);
360         return 0;
361     }
362     if (dns64_env->prefix_net < 0 || dns64_env->prefix_net > 96) {
363         log_err("dns64-prefix length it not between 0 and 96: %s",
364                 cfg->dns64_prefix);
365         return 0;
366     }
367     for(s = cfg->dns64_ignore_aaaa; s; s = s->next) {
368 	    if(!dns64_insert_ignore_aaaa(dns64_env, s->str))
369 		    return 0;
370     }
371     name_tree_init_parents(&dns64_env->ignore_aaaa);
372     return 1;
373 }
374 
375 /**
376  * Initializes this instance of the dns64 module.
377  *
378  * \param env Global state of all module instances.
379  * \param id  This instance's ID number.
380  */
381 int
382 dns64_init(struct module_env* env, int id)
383 {
384     struct dns64_env* dns64_env =
385         (struct dns64_env*)calloc(1, sizeof(struct dns64_env));
386     if (!dns64_env) {
387         log_err("malloc failure");
388         return 0;
389     }
390     env->modinfo[id] = (void*)dns64_env;
391     name_tree_init(&dns64_env->ignore_aaaa);
392     if (!dns64_apply_cfg(dns64_env, env->cfg)) {
393         log_err("dns64: could not apply configuration settings.");
394         return 0;
395     }
396     return 1;
397 }
398 
399 /** free ignore AAAA elements */
400 static void
401 free_ignore_aaaa_node(rbnode_type* node, void* ATTR_UNUSED(arg))
402 {
403 	struct name_tree_node* n = (struct name_tree_node*)node;
404 	if(!n) return;
405 	free(n->name);
406 	free(n);
407 }
408 
409 /**
410  * Deinitializes this instance of the dns64 module.
411  *
412  * \param env Global state of all module instances.
413  * \param id  This instance's ID number.
414  */
415 void
416 dns64_deinit(struct module_env* env, int id)
417 {
418     struct dns64_env* dns64_env;
419     if (!env)
420         return;
421     dns64_env = (struct dns64_env*)env->modinfo[id];
422     if(dns64_env) {
423 	    traverse_postorder(&dns64_env->ignore_aaaa, free_ignore_aaaa_node,
424 	    	NULL);
425     }
426     free(env->modinfo[id]);
427     env->modinfo[id] = NULL;
428 }
429 
430 /**
431  * Handle PTR queries for IPv6 addresses. If the address belongs to the DNS64
432  * prefix, we must do a PTR query for the corresponding IPv4 address instead.
433  *
434  * \param qstate Query state structure.
435  * \param id     This module instance's ID number.
436  *
437  * \return The new state of the query.
438  */
439 static enum module_ext_state
440 handle_ipv6_ptr(struct module_qstate* qstate, int id)
441 {
442     struct dns64_env* dns64_env = (struct dns64_env*)qstate->env->modinfo[id];
443     struct module_qstate* subq = NULL;
444     struct query_info qinfo;
445     struct sockaddr_in6 sin6;
446 
447     /* Convert the PTR query string to an IPv6 address. */
448     memset(&sin6, 0, sizeof(sin6));
449     sin6.sin6_family = AF_INET6;
450     if (!ptr_to_ipv6((char*)qstate->qinfo.qname, sin6.sin6_addr.s6_addr))
451         return module_wait_module;  /* Let other module handle this. */
452 
453     /*
454      * If this IPv6 address is not part of our DNS64 prefix, then we don't need
455      * to do anything. Let another module handle the query.
456      */
457     if (addr_in_common((struct sockaddr_storage*)&sin6, 128,
458                 &dns64_env->prefix_addr, dns64_env->prefix_net,
459                 (socklen_t)sizeof(sin6)) != dns64_env->prefix_net)
460         return module_wait_module;
461 
462     verbose(VERB_ALGO, "dns64: rewrite PTR record");
463 
464     /*
465      * Create a new PTR query info for the domain name corresponding to the IPv4
466      * address corresponding to the IPv6 address corresponding to the original
467      * PTR query domain name.
468      */
469     qinfo = qstate->qinfo;
470     if (!(qinfo.qname = regional_alloc(qstate->region, MAX_PTR_QNAME_IPV4)))
471         return module_error;
472     qinfo.qname_len = ipv4_to_ptr(extract_ipv4(sin6.sin6_addr.s6_addr,
473                 dns64_env->prefix_net), (char*)qinfo.qname);
474 
475     /* Create the new sub-query. */
476     fptr_ok(fptr_whitelist_modenv_attach_sub(qstate->env->attach_sub));
477     if(!(*qstate->env->attach_sub)(qstate, &qinfo, qstate->query_flags, 0, 0,
478                 &subq))
479         return module_error;
480     if (subq) {
481         subq->curmod = id;
482         subq->ext_state[id] = module_state_initial;
483 	subq->minfo[id] = NULL;
484     }
485 
486     return module_wait_subquery;
487 }
488 
489 static enum module_ext_state
490 generate_type_A_query(struct module_qstate* qstate, int id)
491 {
492 	struct module_qstate* subq = NULL;
493 	struct query_info qinfo;
494 
495 	verbose(VERB_ALGO, "dns64: query A record");
496 
497 	/* Create a new query info. */
498 	qinfo = qstate->qinfo;
499 	qinfo.qtype = LDNS_RR_TYPE_A;
500 
501 	/* Start the sub-query. */
502 	fptr_ok(fptr_whitelist_modenv_attach_sub(qstate->env->attach_sub));
503 	if(!(*qstate->env->attach_sub)(qstate, &qinfo, qstate->query_flags, 0,
504 				       0, &subq))
505 	{
506 		verbose(VERB_ALGO, "dns64: sub-query creation failed");
507 		return module_error;
508 	}
509 	if (subq) {
510 		subq->curmod = id;
511 		subq->ext_state[id] = module_state_initial;
512 		subq->minfo[id] = NULL;
513 	}
514 
515 	return module_wait_subquery;
516 }
517 
518 /**
519  * See if query name is in the always synth config.
520  * The ignore-aaaa list has names for which the AAAA for the domain is
521  * ignored and the A is always used to create the answer.
522  * @param qstate: query state.
523  * @param id: module id.
524  * @return true if the name is covered by ignore-aaaa.
525  */
526 static int
527 dns64_always_synth_for_qname(struct module_qstate* qstate, int id)
528 {
529 	struct dns64_env* dns64_env = (struct dns64_env*)qstate->env->modinfo[id];
530 	int labs = dname_count_labels(qstate->qinfo.qname);
531 	struct name_tree_node* node = name_tree_lookup(&dns64_env->ignore_aaaa,
532 		qstate->qinfo.qname, qstate->qinfo.qname_len, labs,
533 		qstate->qinfo.qclass);
534 	return (node != NULL);
535 }
536 
537 /**
538  * Handles the "pass" event for a query. This event is received when a new query
539  * is received by this module. The query may have been generated internally by
540  * another module, in which case we don't want to do any special processing
541  * (this is an interesting discussion topic),  or it may be brand new, e.g.
542  * received over a socket, in which case we do want to apply DNS64 processing.
543  *
544  * \param qstate A structure representing the state of the query that has just
545  *               received the "pass" event.
546  * \param id     This module's instance ID.
547  *
548  * \return The new state of the query.
549  */
550 static enum module_ext_state
551 handle_event_pass(struct module_qstate* qstate, int id)
552 {
553 	struct dns64_qstate* iq = (struct dns64_qstate*)qstate->minfo[id];
554 	if (iq && iq->state == DNS64_NEW_QUERY
555             && qstate->qinfo.qtype == LDNS_RR_TYPE_PTR
556             && qstate->qinfo.qname_len == 74
557             && !strcmp((char*)&qstate->qinfo.qname[64], "\03ip6\04arpa"))
558         /* Handle PTR queries for IPv6 addresses. */
559         return handle_ipv6_ptr(qstate, id);
560 
561 	if (qstate->env->cfg->dns64_synthall &&
562 	    iq && iq->state == DNS64_NEW_QUERY
563 	    && qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA)
564 		return generate_type_A_query(qstate, id);
565 
566 	if(dns64_always_synth_for_qname(qstate, id) &&
567 	    iq && iq->state == DNS64_NEW_QUERY
568 	    && !(qstate->query_flags & BIT_CD)
569 	    && qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA) {
570 		verbose(VERB_ALGO, "dns64: ignore-aaaa and synthesize anyway");
571 		return generate_type_A_query(qstate, id);
572 	}
573 
574 	/* We are finished when our sub-query is finished. */
575 	if (iq && iq->state == DNS64_SUBQUERY_FINISHED)
576 		return module_finished;
577 
578 	/* Otherwise, pass request to next module. */
579 	verbose(VERB_ALGO, "dns64: pass to next module");
580 	return module_wait_module;
581 }
582 
583 /**
584  * Handles the "done" event for a query. We need to analyze the response and
585  * maybe issue a new sub-query for the A record.
586  *
587  * \param qstate A structure representing the state of the query that has just
588  *               received the "pass" event.
589  * \param id     This module's instance ID.
590  *
591  * \return The new state of the query.
592  */
593 static enum module_ext_state
594 handle_event_moddone(struct module_qstate* qstate, int id)
595 {
596 	struct dns64_qstate* iq = (struct dns64_qstate*)qstate->minfo[id];
597     /*
598      * In many cases we have nothing special to do. From most to least common:
599      *
600      *   - An internal query.
601      *   - A query for a record type other than AAAA.
602      *   - CD FLAG was set on querier
603      *   - An AAAA query for which an error was returned.(qstate.return_rcode)
604      *     -> treated as servfail thus synthesize (sec 5.1.3 6147), thus
605      *        synthesize in (sec 5.1.2 of RFC6147).
606      *   - A successful AAAA query with an answer.
607      */
608 	if((!iq || iq->state != DNS64_INTERNAL_QUERY)
609             && qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA
610 	    && !(qstate->query_flags & BIT_CD)
611 	    && !(qstate->return_msg &&
612 		    qstate->return_msg->rep &&
613 		    reply_find_answer_rrset(&qstate->qinfo,
614 			    qstate->return_msg->rep)))
615 		/* not internal, type AAAA, not CD, and no answer RRset,
616 		 * So, this is a AAAA noerror/nodata answer */
617 		return generate_type_A_query(qstate, id);
618 
619 	if((!iq || iq->state != DNS64_INTERNAL_QUERY)
620 	    && qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA
621 	    && !(qstate->query_flags & BIT_CD)
622 	    && dns64_always_synth_for_qname(qstate, id)) {
623 		/* if it is not internal, AAAA, not CD and listed domain,
624 		 * generate from A record and ignore AAAA */
625 		verbose(VERB_ALGO, "dns64: ignore-aaaa and synthesize anyway");
626 		return generate_type_A_query(qstate, id);
627 	}
628 
629 	/* Store the response in cache. */
630 	if ( (!iq || !iq->started_no_cache_store) &&
631 		qstate->return_msg && qstate->return_msg->rep &&
632 		!dns_cache_store(qstate->env, &qstate->qinfo, qstate->return_msg->rep,
633 		0, 0, 0, NULL, qstate->query_flags))
634 		log_err("out of memory");
635 
636 	/* do nothing */
637 	return module_finished;
638 }
639 
640 /**
641  * This is the module's main() function. It gets called each time a query
642  * receives an event which we may need to handle. We respond by updating the
643  * state of the query.
644  *
645  * \param qstate   Structure containing the state of the query.
646  * \param event    Event that has just been received.
647  * \param id       This module's instance ID.
648  * \param outbound State of a DNS query on an authoritative server. We never do
649  *                 our own queries ourselves (other modules do it for us), so
650  *                 this is unused.
651  */
652 void
653 dns64_operate(struct module_qstate* qstate, enum module_ev event, int id,
654 		struct outbound_entry* outbound)
655 {
656 	struct dns64_qstate* iq;
657 	(void)outbound;
658 	verbose(VERB_QUERY, "dns64[module %d] operate: extstate:%s event:%s",
659 			id, strextstate(qstate->ext_state[id]),
660 			strmodulevent(event));
661 	log_query_info(VERB_QUERY, "dns64 operate: query", &qstate->qinfo);
662 
663 	switch(event) {
664 		case module_event_new:
665 			/* Tag this query as being new and fall through. */
666 			iq = (struct dns64_qstate*)regional_alloc(
667 				qstate->region, sizeof(*iq));
668 			qstate->minfo[id] = iq;
669 			iq->state = DNS64_NEW_QUERY;
670 			iq->started_no_cache_store = qstate->no_cache_store;
671 			qstate->no_cache_store = 1;
672   			/* fallthrough */
673 		case module_event_pass:
674 			qstate->ext_state[id] = handle_event_pass(qstate, id);
675 			break;
676 		case module_event_moddone:
677 			qstate->ext_state[id] = handle_event_moddone(qstate, id);
678 			break;
679 		default:
680 			qstate->ext_state[id] = module_finished;
681 			break;
682 	}
683 	if(qstate->ext_state[id] == module_finished) {
684 		iq = (struct dns64_qstate*)qstate->minfo[id];
685 		if(iq && iq->state != DNS64_INTERNAL_QUERY)
686 			qstate->no_cache_store = iq->started_no_cache_store;
687 	}
688 }
689 
690 static void
691 dns64_synth_aaaa_data(const struct ub_packed_rrset_key* fk,
692 		      const struct packed_rrset_data* fd,
693 		      struct ub_packed_rrset_key *dk,
694 		      struct packed_rrset_data **dd_out, struct regional *region,
695 		      struct dns64_env* dns64_env )
696 {
697 	struct packed_rrset_data *dd;
698 	size_t i;
699 	/*
700 	 * Create synthesized AAAA RR set data. We need to allocated extra memory
701 	 * for the RRs themselves. Each RR has a length, TTL, pointer to wireformat
702 	 * data, 2 bytes of data length, and 16 bytes of IPv6 address.
703 	 */
704 	if(fd->count > RR_COUNT_MAX) {
705 		*dd_out = NULL;
706 		return; /* integer overflow protection in alloc */
707 	}
708 	if (!(dd = *dd_out = regional_alloc(region,
709 		  sizeof(struct packed_rrset_data)
710 		  + fd->count * (sizeof(size_t) + sizeof(time_t) +
711 			     sizeof(uint8_t*) + 2 + 16)))) {
712 		log_err("out of memory");
713 		return;
714 	}
715 
716 	/* Copy attributes from A RR set. */
717 	dd->ttl = fd->ttl;
718 	dd->count = fd->count;
719 	dd->rrsig_count = 0;
720 	dd->trust = fd->trust;
721 	dd->security = fd->security;
722 
723 	/*
724 	 * Synthesize AAAA records. Adjust pointers in structure.
725 	 */
726 	dd->rr_len =
727 	    (size_t*)((uint8_t*)dd + sizeof(struct packed_rrset_data));
728 	dd->rr_data = (uint8_t**)&dd->rr_len[dd->count];
729 	dd->rr_ttl = (time_t*)&dd->rr_data[dd->count];
730 	for(i = 0; i < fd->count; ++i) {
731 		if (fd->rr_len[i] != 6 || fd->rr_data[i][0] != 0
732 		    || fd->rr_data[i][1] != 4) {
733 			*dd_out = NULL;
734 			return;
735 		}
736 		dd->rr_len[i] = 18;
737 		dd->rr_data[i] =
738 		    (uint8_t*)&dd->rr_ttl[dd->count] + 18*i;
739 		dd->rr_data[i][0] = 0;
740 		dd->rr_data[i][1] = 16;
741 		synthesize_aaaa(
742 				((struct sockaddr_in6*)&dns64_env->prefix_addr)->sin6_addr.s6_addr,
743 				dns64_env->prefix_net, &fd->rr_data[i][2],
744 				&dd->rr_data[i][2] );
745 		dd->rr_ttl[i] = fd->rr_ttl[i];
746 	}
747 
748 	/*
749 	 * Create synthesized AAAA RR set key. This is mostly just bookkeeping,
750 	 * nothing interesting here.
751 	 */
752 	if(!dk) {
753 		log_err("no key");
754 		*dd_out = NULL;
755 		return;
756 	}
757 
758 	dk->rk.dname = (uint8_t*)regional_alloc_init(region,
759 		     fk->rk.dname, fk->rk.dname_len);
760 
761 	if(!dk->rk.dname) {
762 		log_err("out of memory");
763 		*dd_out = NULL;
764 		return;
765 	}
766 
767 	dk->rk.type = htons(LDNS_RR_TYPE_AAAA);
768 	memset(&dk->entry, 0, sizeof(dk->entry));
769 	dk->entry.key = dk;
770 	dk->entry.hash = rrset_key_hash(&dk->rk);
771 	dk->entry.data = dd;
772 
773 }
774 
775 /**
776  * Synthesize an AAAA RR set from an A sub-query's answer and add it to the
777  * original empty response.
778  *
779  * \param id     This module's instance ID.
780  * \param super  Original AAAA query.
781  * \param qstate A query.
782  */
783 static void
784 dns64_adjust_a(int id, struct module_qstate* super, struct module_qstate* qstate)
785 {
786 	struct dns64_env* dns64_env = (struct dns64_env*)super->env->modinfo[id];
787 	struct reply_info *rep, *cp;
788 	size_t i, s;
789 	struct packed_rrset_data* fd, *dd;
790 	struct ub_packed_rrset_key* fk, *dk;
791 
792 	verbose(VERB_ALGO, "converting A answers to AAAA answers");
793 
794 	log_assert(super->region);
795 	log_assert(qstate->return_msg);
796 	log_assert(qstate->return_msg->rep);
797 
798 	/* If dns64-synthall is enabled, return_msg is not initialized */
799 	if(!super->return_msg) {
800 		super->return_msg = (struct dns_msg*)regional_alloc(
801 		    super->region, sizeof(struct dns_msg));
802 		if(!super->return_msg)
803 			return;
804 		memset(super->return_msg, 0, sizeof(*super->return_msg));
805 		super->return_msg->qinfo = super->qinfo;
806 	}
807 
808 	rep = qstate->return_msg->rep;
809 
810 	/*
811 	 * Build the actual reply.
812 	 */
813 	cp = construct_reply_info_base(super->region, rep->flags, rep->qdcount,
814 		rep->ttl, rep->prefetch_ttl, rep->serve_expired_ttl,
815 		rep->an_numrrsets, rep->ns_numrrsets, rep->ar_numrrsets,
816 		rep->rrset_count, rep->security);
817 	if(!cp)
818 		return;
819 
820 	/* allocate ub_key structures special or not */
821 	if(!reply_info_alloc_rrset_keys(cp, NULL, super->region)) {
822 		return;
823 	}
824 
825 	/* copy everything and replace A by AAAA */
826 	for(i=0; i<cp->rrset_count; i++) {
827 		fk = rep->rrsets[i];
828 		dk = cp->rrsets[i];
829 		fd = (struct packed_rrset_data*)fk->entry.data;
830 		dk->rk = fk->rk;
831 		dk->id = fk->id;
832 
833 		if(i<rep->an_numrrsets && fk->rk.type == htons(LDNS_RR_TYPE_A)) {
834 			/* also sets dk->entry.hash */
835 			dns64_synth_aaaa_data(fk, fd, dk, &dd, super->region, dns64_env);
836 			if(!dd)
837 				return;
838 			/* Delete negative AAAA record from cache stored by
839 			 * the iterator module */
840 			rrset_cache_remove(super->env->rrset_cache, dk->rk.dname,
841 					   dk->rk.dname_len, LDNS_RR_TYPE_AAAA,
842 					   LDNS_RR_CLASS_IN, 0);
843 			/* Delete negative AAAA in msg cache for CNAMEs,
844 			 * stored by the iterator module */
845 			if(i != 0) /* if not the first RR */
846 			    msg_cache_remove(super->env, dk->rk.dname,
847 				dk->rk.dname_len, LDNS_RR_TYPE_AAAA,
848 				LDNS_RR_CLASS_IN, 0);
849 		} else {
850 			dk->entry.hash = fk->entry.hash;
851 			dk->rk.dname = (uint8_t*)regional_alloc_init(super->region,
852 				fk->rk.dname, fk->rk.dname_len);
853 
854 			if(!dk->rk.dname)
855 				return;
856 
857 			s = packed_rrset_sizeof(fd);
858 			dd = (struct packed_rrset_data*)regional_alloc_init(
859 				super->region, fd, s);
860 
861 			if(!dd)
862 				return;
863 		}
864 
865 		packed_rrset_ptr_fixup(dd);
866 		dk->entry.data = (void*)dd;
867 	}
868 
869 	/* Commit changes. */
870 	super->return_msg->rep = cp;
871 }
872 
873 /**
874  * Generate a response for the original IPv6 PTR query based on an IPv4 PTR
875  * sub-query's response.
876  *
877  * \param qstate IPv4 PTR sub-query.
878  * \param super  Original IPv6 PTR query.
879  */
880 static void
881 dns64_adjust_ptr(struct module_qstate* qstate, struct module_qstate* super)
882 {
883     struct ub_packed_rrset_key* answer;
884 
885     verbose(VERB_ALGO, "adjusting PTR reply");
886 
887     /* Copy the sub-query's reply to the parent. */
888     if (!(super->return_msg = (struct dns_msg*)regional_alloc(super->region,
889                     sizeof(struct dns_msg))))
890         return;
891     super->return_msg->qinfo = super->qinfo;
892     super->return_msg->rep = reply_info_copy(qstate->return_msg->rep, NULL,
893             super->region);
894 
895     /*
896      * Adjust the domain name of the answer RR set so that it matches the
897      * initial query's domain name.
898      */
899     answer = reply_find_answer_rrset(&qstate->qinfo, super->return_msg->rep);
900     if(answer) {
901 	    answer->rk.dname = super->qinfo.qname;
902 	    answer->rk.dname_len = super->qinfo.qname_len;
903     }
904 }
905 
906 /**
907  * This function is called when a sub-query finishes to inform the parent query.
908  *
909  * We issue two kinds of sub-queries: PTR and A.
910  *
911  * \param qstate State of the sub-query.
912  * \param id     This module's instance ID.
913  * \param super  State of the super-query.
914  */
915 void
916 dns64_inform_super(struct module_qstate* qstate, int id,
917 		struct module_qstate* super)
918 {
919 	struct dns64_qstate* super_dq = (struct dns64_qstate*)super->minfo[id];
920 	log_query_info(VERB_ALGO, "dns64: inform_super, sub is",
921 		       &qstate->qinfo);
922 	log_query_info(VERB_ALGO, "super is", &super->qinfo);
923 
924 	/*
925 	 * Signal that the sub-query is finished, no matter whether we are
926 	 * successful or not. This lets the state machine terminate.
927 	 */
928 	if(!super_dq) {
929 		super_dq = (struct dns64_qstate*)regional_alloc(super->region,
930 			sizeof(*super_dq));
931 		super->minfo[id] = super_dq;
932 		memset(super_dq, 0, sizeof(*super_dq));
933 		super_dq->started_no_cache_store = super->no_cache_store;
934 	}
935 	super_dq->state = DNS64_SUBQUERY_FINISHED;
936 
937 	/* If there is no successful answer, we're done. */
938 	if (qstate->return_rcode != LDNS_RCODE_NOERROR
939 	    || !qstate->return_msg
940 	    || !qstate->return_msg->rep) {
941 		return;
942 	}
943 
944 	/* Use return code from A query in response to client. */
945 	if (super->return_rcode != LDNS_RCODE_NOERROR)
946 		super->return_rcode = qstate->return_rcode;
947 
948 	/* Generate a response suitable for the original query. */
949 	if (qstate->qinfo.qtype == LDNS_RR_TYPE_A) {
950 		dns64_adjust_a(id, super, qstate);
951 	} else {
952 		log_assert(qstate->qinfo.qtype == LDNS_RR_TYPE_PTR);
953 		dns64_adjust_ptr(qstate, super);
954 	}
955 
956 	/* Store the generated response in cache. */
957 	if ( (!super_dq || !super_dq->started_no_cache_store) &&
958 		!dns_cache_store(super->env, &super->qinfo, super->return_msg->rep,
959 		0, 0, 0, NULL, super->query_flags))
960 		log_err("out of memory");
961 }
962 
963 /**
964  * Clear module-specific data from query state. Since we do not allocate memory,
965  * it's just a matter of setting a pointer to NULL.
966  *
967  * \param qstate Query state.
968  * \param id     This module's instance ID.
969  */
970 void
971 dns64_clear(struct module_qstate* qstate, int id)
972 {
973     qstate->minfo[id] = NULL;
974 }
975 
976 /**
977  * Returns the amount of global memory that this module uses, not including
978  * per-query data.
979  *
980  * \param env Module environment.
981  * \param id  This module's instance ID.
982  */
983 size_t
984 dns64_get_mem(struct module_env* env, int id)
985 {
986     struct dns64_env* dns64_env = (struct dns64_env*)env->modinfo[id];
987     if (!dns64_env)
988         return 0;
989     return sizeof(*dns64_env);
990 }
991 
992 /**
993  * The dns64 function block.
994  */
995 static struct module_func_block dns64_block = {
996 	"dns64",
997 	&dns64_init, &dns64_deinit, &dns64_operate, &dns64_inform_super,
998 	&dns64_clear, &dns64_get_mem
999 };
1000 
1001 /**
1002  * Function for returning the above function block.
1003  */
1004 struct module_func_block *
1005 dns64_get_funcblock(void)
1006 {
1007 	return &dns64_block;
1008 }
1009