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