xref: /freebsd/contrib/unbound/respip/respip.c (revision 848ee2a3a8b47c9905fc51fefcf60eb371edbb98)
1 /*
2  * respip/respip.c - filtering response IP module
3  */
4 
5 /**
6  * \file
7  *
8  * This file contains a module that inspects a result of recursive resolution
9  * to see if any IP address record should trigger a special action.
10  * If applicable these actions can modify the original response.
11  */
12 #include "config.h"
13 
14 #include "services/localzone.h"
15 #include "services/authzone.h"
16 #include "services/cache/dns.h"
17 #include "sldns/str2wire.h"
18 #include "util/config_file.h"
19 #include "util/fptr_wlist.h"
20 #include "util/module.h"
21 #include "util/net_help.h"
22 #include "util/regional.h"
23 #include "util/data/msgreply.h"
24 #include "util/storage/dnstree.h"
25 #include "respip/respip.h"
26 #include "services/view.h"
27 #include "sldns/rrdef.h"
28 
29 
30 /** Subset of resp_addr.node, used for inform-variant logging */
31 struct respip_addr_info {
32 	struct sockaddr_storage addr;
33 	socklen_t addrlen;
34 	int net;
35 };
36 
37 /** Query state regarding the response-ip module. */
38 enum respip_state {
39 	/**
40 	 * The general state.  Unless CNAME chasing takes place, all processing
41 	 * is completed in this state without any other asynchronous event.
42 	 */
43 	RESPIP_INIT = 0,
44 
45 	/**
46 	 * A subquery for CNAME chasing is completed.
47 	 */
48 	RESPIP_SUBQUERY_FINISHED
49 };
50 
51 /** Per query state for the response-ip module. */
52 struct respip_qstate {
53 	enum respip_state state;
54 };
55 
56 struct respip_set*
57 respip_set_create(void)
58 {
59 	struct respip_set* set = calloc(1, sizeof(*set));
60 	if(!set)
61 		return NULL;
62 	set->region = regional_create();
63 	if(!set->region) {
64 		free(set);
65 		return NULL;
66 	}
67 	addr_tree_init(&set->ip_tree);
68 	lock_rw_init(&set->lock);
69 	return set;
70 }
71 
72 /** helper traverse to delete resp_addr nodes */
73 static void
74 resp_addr_del(rbnode_type* n, void* ATTR_UNUSED(arg))
75 {
76 	struct resp_addr* r = (struct resp_addr*)n->key;
77 	lock_rw_destroy(&r->lock);
78 #ifdef THREADS_DISABLED
79 	(void)r;
80 #endif
81 }
82 
83 void
84 respip_set_delete(struct respip_set* set)
85 {
86 	if(!set)
87 		return;
88 	lock_rw_destroy(&set->lock);
89 	traverse_postorder(&set->ip_tree, resp_addr_del, NULL);
90 	regional_destroy(set->region);
91 	free(set);
92 }
93 
94 struct rbtree_type*
95 respip_set_get_tree(struct respip_set* set)
96 {
97 	if(!set)
98 		return NULL;
99 	return &set->ip_tree;
100 }
101 
102 struct resp_addr*
103 respip_sockaddr_find_or_create(struct respip_set* set, struct sockaddr_storage* addr,
104 		socklen_t addrlen, int net, int create, const char* ipstr)
105 {
106 	struct resp_addr* node;
107 	node = (struct resp_addr*)addr_tree_find(&set->ip_tree, addr, addrlen, net);
108 	if(!node && create) {
109 		node = regional_alloc_zero(set->region, sizeof(*node));
110 		if(!node) {
111 			log_err("out of memory");
112 			return NULL;
113 		}
114 		lock_rw_init(&node->lock);
115 		node->action = respip_none;
116 		if(!addr_tree_insert(&set->ip_tree, &node->node, addr,
117 			addrlen, net)) {
118 			/* We know we didn't find it, so this should be
119 			 * impossible. */
120 			log_warn("unexpected: duplicate address: %s", ipstr);
121 		}
122 	}
123 	return node;
124 }
125 
126 void
127 respip_sockaddr_delete(struct respip_set* set, struct resp_addr* node)
128 {
129 	struct resp_addr* prev;
130 	prev = (struct resp_addr*)rbtree_previous((struct rbnode_type*)node);
131 	lock_rw_destroy(&node->lock);
132 	(void)rbtree_delete(&set->ip_tree, node);
133 	/* no free'ing, all allocated in region */
134 	if(!prev)
135 		addr_tree_init_parents((rbtree_type*)set);
136 	else
137 		addr_tree_init_parents_node(&prev->node);
138 }
139 
140 /** returns the node in the address tree for the specified netblock string;
141  * non-existent node will be created if 'create' is true */
142 static struct resp_addr*
143 respip_find_or_create(struct respip_set* set, const char* ipstr, int create)
144 {
145 	struct sockaddr_storage addr;
146 	int net;
147 	socklen_t addrlen;
148 
149 	if(!netblockstrtoaddr(ipstr, 0, &addr, &addrlen, &net)) {
150 		log_err("cannot parse netblock: '%s'", ipstr);
151 		return NULL;
152 	}
153 	return respip_sockaddr_find_or_create(set, &addr, addrlen, net, create,
154 		ipstr);
155 }
156 
157 static int
158 respip_tag_cfg(struct respip_set* set, const char* ipstr,
159 	const uint8_t* taglist, size_t taglen)
160 {
161 	struct resp_addr* node;
162 
163 	if(!(node=respip_find_or_create(set, ipstr, 1)))
164 		return 0;
165 	if(node->taglist) {
166 		log_warn("duplicate response-address-tag for '%s', overridden.",
167 			ipstr);
168 	}
169 	node->taglist = regional_alloc_init(set->region, taglist, taglen);
170 	if(!node->taglist) {
171 		log_err("out of memory");
172 		return 0;
173 	}
174 	node->taglen = taglen;
175 	return 1;
176 }
177 
178 /** set action for the node specified by the netblock string */
179 static int
180 respip_action_cfg(struct respip_set* set, const char* ipstr,
181 	const char* actnstr)
182 {
183 	struct resp_addr* node;
184 	enum respip_action action;
185 
186 	if(!(node=respip_find_or_create(set, ipstr, 1)))
187 		return 0;
188 	if(node->action != respip_none) {
189 		verbose(VERB_QUERY, "duplicate response-ip action for '%s', overridden.",
190 			ipstr);
191 	}
192         if(strcmp(actnstr, "deny") == 0)
193                 action = respip_deny;
194         else if(strcmp(actnstr, "redirect") == 0)
195                 action = respip_redirect;
196         else if(strcmp(actnstr, "inform") == 0)
197                 action = respip_inform;
198         else if(strcmp(actnstr, "inform_deny") == 0)
199                 action = respip_inform_deny;
200         else if(strcmp(actnstr, "inform_redirect") == 0)
201                 action = respip_inform_redirect;
202         else if(strcmp(actnstr, "always_transparent") == 0)
203                 action = respip_always_transparent;
204         else if(strcmp(actnstr, "always_refuse") == 0)
205                 action = respip_always_refuse;
206         else if(strcmp(actnstr, "always_nxdomain") == 0)
207                 action = respip_always_nxdomain;
208         else if(strcmp(actnstr, "always_nodata") == 0)
209                 action = respip_always_nodata;
210         else if(strcmp(actnstr, "always_deny") == 0)
211                 action = respip_always_deny;
212         else {
213                 log_err("unknown response-ip action %s", actnstr);
214                 return 0;
215         }
216 	node->action = action;
217 	return 1;
218 }
219 
220 /** allocate and initialize an rrset structure; this function is based
221  * on new_local_rrset() from the localzone.c module */
222 static struct ub_packed_rrset_key*
223 new_rrset(struct regional* region, uint16_t rrtype, uint16_t rrclass)
224 {
225 	struct packed_rrset_data* pd;
226 	struct ub_packed_rrset_key* rrset = regional_alloc_zero(
227 		region, sizeof(*rrset));
228 	if(!rrset) {
229 		log_err("out of memory");
230 		return NULL;
231 	}
232 	rrset->entry.key = rrset;
233 	pd = regional_alloc_zero(region, sizeof(*pd));
234 	if(!pd) {
235 		log_err("out of memory");
236 		return NULL;
237 	}
238 	pd->trust = rrset_trust_prim_noglue;
239 	pd->security = sec_status_insecure;
240 	rrset->entry.data = pd;
241 	rrset->rk.dname = regional_alloc_zero(region, 1);
242 	if(!rrset->rk.dname) {
243 		log_err("out of memory");
244 		return NULL;
245 	}
246 	rrset->rk.dname_len = 1;
247 	rrset->rk.type = htons(rrtype);
248 	rrset->rk.rrset_class = htons(rrclass);
249 	return rrset;
250 }
251 
252 /** enter local data as resource records into a response-ip node */
253 
254 int
255 respip_enter_rr(struct regional* region, struct resp_addr* raddr,
256 	uint16_t rrtype, uint16_t rrclass, time_t ttl, uint8_t* rdata,
257 	size_t rdata_len, const char* rrstr, const char* netblockstr)
258 {
259 	struct packed_rrset_data* pd;
260 	struct sockaddr* sa;
261 	sa = (struct sockaddr*)&raddr->node.addr;
262 	if (rrtype == LDNS_RR_TYPE_CNAME && raddr->data) {
263 		log_err("CNAME response-ip data (%s) can not co-exist with other "
264 			"response-ip data for netblock %s", rrstr, netblockstr);
265 		return 0;
266 	} else if (raddr->data &&
267 		raddr->data->rk.type == htons(LDNS_RR_TYPE_CNAME)) {
268 		log_err("response-ip data (%s) can not be added; CNAME response-ip "
269 			"data already in place for netblock %s", rrstr, netblockstr);
270 		return 0;
271 	} else if((rrtype != LDNS_RR_TYPE_CNAME) &&
272 		((sa->sa_family == AF_INET && rrtype != LDNS_RR_TYPE_A) ||
273 		(sa->sa_family == AF_INET6 && rrtype != LDNS_RR_TYPE_AAAA))) {
274 		log_err("response-ip data %s record type does not correspond "
275 			"to netblock %s address family", rrstr, netblockstr);
276 		return 0;
277 	}
278 
279 	if(!raddr->data) {
280 		raddr->data = new_rrset(region, rrtype, rrclass);
281 		if(!raddr->data)
282 			return 0;
283 	}
284 	pd = raddr->data->entry.data;
285 	return rrset_insert_rr(region, pd, rdata, rdata_len, ttl, rrstr);
286 }
287 
288 static int
289 respip_enter_rrstr(struct regional* region, struct resp_addr* raddr,
290 		const char* rrstr, const char* netblock)
291 {
292 	uint8_t* nm;
293 	uint16_t rrtype = 0, rrclass = 0;
294 	time_t ttl = 0;
295 	uint8_t rr[LDNS_RR_BUF_SIZE];
296 	uint8_t* rdata = NULL;
297 	size_t rdata_len = 0;
298 	char buf[65536];
299 	char bufshort[64];
300 	int ret;
301 	if(raddr->action != respip_redirect
302 		&& raddr->action != respip_inform_redirect) {
303 		log_err("cannot parse response-ip-data %s: response-ip "
304 			"action for %s is not redirect", rrstr, netblock);
305 		return 0;
306 	}
307 	ret = snprintf(buf, sizeof(buf), ". %s", rrstr);
308 	if(ret < 0 || ret >= (int)sizeof(buf)) {
309 		strlcpy(bufshort, rrstr, sizeof(bufshort));
310 		log_err("bad response-ip-data: %s...", bufshort);
311 		return 0;
312 	}
313 	if(!rrstr_get_rr_content(buf, &nm, &rrtype, &rrclass, &ttl, rr, sizeof(rr),
314 		&rdata, &rdata_len)) {
315 		log_err("bad response-ip-data: %s", rrstr);
316 		return 0;
317 	}
318 	free(nm);
319 	return respip_enter_rr(region, raddr, rrtype, rrclass, ttl, rdata,
320 		rdata_len, rrstr, netblock);
321 }
322 
323 static int
324 respip_data_cfg(struct respip_set* set, const char* ipstr, const char* rrstr)
325 {
326 	struct resp_addr* node;
327 
328 	node=respip_find_or_create(set, ipstr, 0);
329 	if(!node || node->action == respip_none) {
330 		log_err("cannot parse response-ip-data %s: "
331 			"response-ip node for %s not found", rrstr, ipstr);
332 		return 0;
333 	}
334 	return respip_enter_rrstr(set->region, node, rrstr, ipstr);
335 }
336 
337 static int
338 respip_set_apply_cfg(struct respip_set* set, char* const* tagname, int num_tags,
339 	struct config_strbytelist* respip_tags,
340 	struct config_str2list* respip_actions,
341 	struct config_str2list* respip_data)
342 {
343 	struct config_strbytelist* p;
344 	struct config_str2list* pa;
345 	struct config_str2list* pd;
346 
347 	set->tagname = tagname;
348 	set->num_tags = num_tags;
349 
350 	p = respip_tags;
351 	while(p) {
352 		struct config_strbytelist* np = p->next;
353 
354 		log_assert(p->str && p->str2);
355 		if(!respip_tag_cfg(set, p->str, p->str2, p->str2len)) {
356 			config_del_strbytelist(p);
357 			return 0;
358 		}
359 		free(p->str);
360 		free(p->str2);
361 		free(p);
362 		p = np;
363 	}
364 
365 	pa = respip_actions;
366 	while(pa) {
367 		struct config_str2list* np = pa->next;
368 		log_assert(pa->str && pa->str2);
369 		if(!respip_action_cfg(set, pa->str, pa->str2)) {
370 			config_deldblstrlist(pa);
371 			return 0;
372 		}
373 		free(pa->str);
374 		free(pa->str2);
375 		free(pa);
376 		pa = np;
377 	}
378 
379 	pd = respip_data;
380 	while(pd) {
381 		struct config_str2list* np = pd->next;
382 		log_assert(pd->str && pd->str2);
383 		if(!respip_data_cfg(set, pd->str, pd->str2)) {
384 			config_deldblstrlist(pd);
385 			return 0;
386 		}
387 		free(pd->str);
388 		free(pd->str2);
389 		free(pd);
390 		pd = np;
391 	}
392 	addr_tree_init_parents(&set->ip_tree);
393 
394 	return 1;
395 }
396 
397 int
398 respip_global_apply_cfg(struct respip_set* set, struct config_file* cfg)
399 {
400 	int ret = respip_set_apply_cfg(set, cfg->tagname, cfg->num_tags,
401 		cfg->respip_tags, cfg->respip_actions, cfg->respip_data);
402 	cfg->respip_data = NULL;
403 	cfg->respip_actions = NULL;
404 	cfg->respip_tags = NULL;
405 	return ret;
406 }
407 
408 /** Iterate through raw view data and apply the view-specific respip
409  * configuration; at this point we should have already seen all the views,
410  * so if any of the views that respip data refer to does not exist, that's
411  * an error.  This additional iteration through view configuration data
412  * is expected to not have significant performance impact (or rather, its
413  * performance impact is not expected to be prohibitive in the configuration
414  * processing phase).
415  */
416 int
417 respip_views_apply_cfg(struct views* vs, struct config_file* cfg,
418 	int* have_view_respip_cfg)
419 {
420 	struct config_view* cv;
421 	struct view* v;
422 	int ret;
423 
424 	for(cv = cfg->views; cv; cv = cv->next) {
425 
426 		/** if no respip config for this view then there's
427 		  * nothing to do; note that even though respip data must go
428 		  * with respip action, we're checking for both here because
429 		  * we want to catch the case where the respip action is missing
430 		  * while the data is present */
431 		if(!cv->respip_actions && !cv->respip_data)
432 			continue;
433 
434 		if(!(v = views_find_view(vs, cv->name, 1))) {
435 			log_err("view '%s' unexpectedly missing", cv->name);
436 			return 0;
437 		}
438 		if(!v->respip_set) {
439 			v->respip_set = respip_set_create();
440 			if(!v->respip_set) {
441 				log_err("out of memory");
442 				lock_rw_unlock(&v->lock);
443 				return 0;
444 			}
445 		}
446 		ret = respip_set_apply_cfg(v->respip_set, NULL, 0, NULL,
447 			cv->respip_actions, cv->respip_data);
448 		lock_rw_unlock(&v->lock);
449 		if(!ret) {
450 			log_err("Error while applying respip configuration "
451 				"for view '%s'", cv->name);
452 			return 0;
453 		}
454 		*have_view_respip_cfg = (*have_view_respip_cfg ||
455 			v->respip_set->ip_tree.count);
456 		cv->respip_actions = NULL;
457 		cv->respip_data = NULL;
458 	}
459 	return 1;
460 }
461 
462 /**
463  * make a deep copy of 'key' in 'region'.
464  * This is largely derived from packed_rrset_copy_region() and
465  * packed_rrset_ptr_fixup(), but differs in the following points:
466  *
467  * - It doesn't assume all data in 'key' are in a contiguous memory region.
468  *   Although that would be the case in most cases, 'key' can be passed from
469  *   a lower-level module and it might not build the rrset to meet the
470  *   assumption.  In fact, an rrset specified as response-ip-data or generated
471  *   in local_data_find_tag_datas() breaks the assumption.  So it would be
472  *   safer not to naively rely on the assumption.  On the other hand, this
473  *   function ensures the copied rrset data are in a contiguous region so
474  *   that it won't cause a disruption even if an upper layer module naively
475  *   assumes the memory layout.
476  * - It doesn't copy RRSIGs (if any) in 'key'.  The rrset will be used in
477  *   a reply that was already faked, so it doesn't make much sense to provide
478  *   partial sigs even if they are valid themselves.
479  * - It doesn't adjust TTLs as it basically has to be a verbatim copy of 'key'
480  *   just allocated in 'region' (the assumption is necessary TTL adjustment
481  *   has been already done in 'key').
482  *
483  * This function returns the copied rrset key on success, and NULL on memory
484  * allocation failure.
485  */
486 static struct ub_packed_rrset_key*
487 copy_rrset(const struct ub_packed_rrset_key* key, struct regional* region)
488 {
489 	struct ub_packed_rrset_key* ck = regional_alloc(region,
490 		sizeof(struct ub_packed_rrset_key));
491 	struct packed_rrset_data* d;
492 	struct packed_rrset_data* data = key->entry.data;
493 	size_t dsize, i;
494 	uint8_t* nextrdata;
495 
496 	/* derived from packed_rrset_copy_region(), but don't use
497 	 * packed_rrset_sizeof() and do exclude RRSIGs */
498 	if(!ck)
499 		return NULL;
500 	ck->id = key->id;
501 	memset(&ck->entry, 0, sizeof(ck->entry));
502 	ck->entry.hash = key->entry.hash;
503 	ck->entry.key = ck;
504 	ck->rk = key->rk;
505 	if(key->rk.dname) {
506 		ck->rk.dname = regional_alloc_init(region, key->rk.dname,
507 			key->rk.dname_len);
508 		if(!ck->rk.dname)
509 			return NULL;
510 		ck->rk.dname_len = key->rk.dname_len;
511 	} else {
512 		ck->rk.dname = NULL;
513 		ck->rk.dname_len = 0;
514 	}
515 
516 	if((unsigned)data->count >= 0xffff00U)
517 		return NULL; /* guard against integer overflow in dsize */
518 	dsize = sizeof(struct packed_rrset_data) + data->count *
519 		(sizeof(size_t)+sizeof(uint8_t*)+sizeof(time_t));
520 	for(i=0; i<data->count; i++) {
521 		if((unsigned)dsize >= 0x0fffffffU ||
522 			(unsigned)data->rr_len[i] >= 0x0fffffffU)
523 			return NULL; /* guard against integer overflow */
524 		dsize += data->rr_len[i];
525 	}
526 	d = regional_alloc_zero(region, dsize);
527 	if(!d)
528 		return NULL;
529 	*d = *data;
530 	d->rrsig_count = 0;
531 	ck->entry.data = d;
532 
533 	/* derived from packed_rrset_ptr_fixup() with copying the data */
534 	d->rr_len = (size_t*)((uint8_t*)d + sizeof(struct packed_rrset_data));
535 	d->rr_data = (uint8_t**)&(d->rr_len[d->count]);
536 	d->rr_ttl = (time_t*)&(d->rr_data[d->count]);
537 	nextrdata = (uint8_t*)&(d->rr_ttl[d->count]);
538 	for(i=0; i<d->count; i++) {
539 		d->rr_len[i] = data->rr_len[i];
540 		d->rr_ttl[i] = data->rr_ttl[i];
541 		d->rr_data[i] = nextrdata;
542 		memcpy(d->rr_data[i], data->rr_data[i], data->rr_len[i]);
543 		nextrdata += d->rr_len[i];
544 	}
545 
546 	return ck;
547 }
548 
549 int
550 respip_init(struct module_env* env, int id)
551 {
552 	(void)env;
553 	(void)id;
554 	return 1;
555 }
556 
557 void
558 respip_deinit(struct module_env* env, int id)
559 {
560 	(void)env;
561 	(void)id;
562 }
563 
564 /** Convert a packed AAAA or A RRset to sockaddr. */
565 static int
566 rdata2sockaddr(const struct packed_rrset_data* rd, uint16_t rtype, size_t i,
567 	struct sockaddr_storage* ss, socklen_t* addrlenp)
568 {
569 	/* unbound can accept and cache odd-length AAAA/A records, so we have
570 	 * to validate the length. */
571 	if(rtype == LDNS_RR_TYPE_A && rd->rr_len[i] == 6) {
572 		struct sockaddr_in* sa4 = (struct sockaddr_in*)ss;
573 
574 		memset(sa4, 0, sizeof(*sa4));
575 		sa4->sin_family = AF_INET;
576 		memcpy(&sa4->sin_addr, rd->rr_data[i] + 2,
577 			sizeof(sa4->sin_addr));
578 		*addrlenp = sizeof(*sa4);
579 		return 1;
580 	} else if(rtype == LDNS_RR_TYPE_AAAA && rd->rr_len[i] == 18) {
581 		struct sockaddr_in6* sa6 = (struct sockaddr_in6*)ss;
582 
583 		memset(sa6, 0, sizeof(*sa6));
584 		sa6->sin6_family = AF_INET6;
585 		memcpy(&sa6->sin6_addr, rd->rr_data[i] + 2,
586 			sizeof(sa6->sin6_addr));
587 		*addrlenp = sizeof(*sa6);
588 		return 1;
589 	}
590 	return 0;
591 }
592 
593 /**
594  * Search the given 'iptree' for response address information that matches
595  * any of the IP addresses in an AAAA or A in the answer section of the
596  * response (stored in 'rep').  If found, a pointer to the matched resp_addr
597  * structure will be returned, and '*rrset_id' is set to the index in
598  * rep->rrsets for the RRset that contains the matching IP address record
599  * (the index is normally 0, but can be larger than that if this is a CNAME
600  * chain or type-ANY response).
601  * Returns resp_addr holding read lock.
602  */
603 static struct resp_addr*
604 respip_addr_lookup(const struct reply_info *rep, struct respip_set* rs,
605 	size_t* rrset_id)
606 {
607 	size_t i;
608 	struct resp_addr* ra;
609 	struct sockaddr_storage ss;
610 	socklen_t addrlen;
611 
612 	lock_rw_rdlock(&rs->lock);
613 	for(i=0; i<rep->an_numrrsets; i++) {
614 		size_t j;
615 		const struct packed_rrset_data* rd;
616 		uint16_t rtype = ntohs(rep->rrsets[i]->rk.type);
617 
618 		if(rtype != LDNS_RR_TYPE_A && rtype != LDNS_RR_TYPE_AAAA)
619 			continue;
620 		rd = rep->rrsets[i]->entry.data;
621 		for(j = 0; j < rd->count; j++) {
622 			if(!rdata2sockaddr(rd, rtype, j, &ss, &addrlen))
623 				continue;
624 			ra = (struct resp_addr*)addr_tree_lookup(&rs->ip_tree,
625 				&ss, addrlen);
626 			if(ra) {
627 				*rrset_id = i;
628 				lock_rw_rdlock(&ra->lock);
629 				lock_rw_unlock(&rs->lock);
630 				return ra;
631 			}
632 		}
633 	}
634 	lock_rw_unlock(&rs->lock);
635 	return NULL;
636 }
637 
638 /*
639  * Create a new reply_info based on 'rep'.  The new info is based on
640  * the passed 'rep', but ignores any rrsets except for the first 'an_numrrsets'
641  * RRsets in the answer section.  These answer rrsets are copied to the
642  * new info, up to 'copy_rrsets' rrsets (which must not be larger than
643  * 'an_numrrsets').  If an_numrrsets > copy_rrsets, the remaining rrsets array
644  * entries will be kept empty so the caller can fill them later.  When rrsets
645  * are copied, they are shallow copied.  The caller must ensure that the
646  * copied rrsets are valid throughout its lifetime and must provide appropriate
647  * mutex if it can be shared by multiple threads.
648  */
649 static struct reply_info *
650 make_new_reply_info(const struct reply_info* rep, struct regional* region,
651 	size_t an_numrrsets, size_t copy_rrsets)
652 {
653 	struct reply_info* new_rep;
654 	size_t i;
655 
656 	/* create a base struct.  we specify 'insecure' security status as
657 	 * the modified response won't be DNSSEC-valid.  In our faked response
658 	 * the authority and additional sections will be empty (except possible
659 	 * EDNS0 OPT RR in the additional section appended on sending it out),
660 	 * so the total number of RRsets is an_numrrsets. */
661 	new_rep = construct_reply_info_base(region, rep->flags,
662 		rep->qdcount, rep->ttl, rep->prefetch_ttl,
663 		rep->serve_expired_ttl, an_numrrsets, 0, 0, an_numrrsets,
664 		sec_status_insecure);
665 	if(!new_rep)
666 		return NULL;
667 	if(!reply_info_alloc_rrset_keys(new_rep, NULL, region))
668 		return NULL;
669 	for(i=0; i<copy_rrsets; i++)
670 		new_rep->rrsets[i] = rep->rrsets[i];
671 
672 	return new_rep;
673 }
674 
675 /**
676  * See if response-ip or tag data should override the original answer rrset
677  * (which is rep->rrsets[rrset_id]) and if so override it.
678  * This is (mostly) equivalent to localzone.c:local_data_answer() but for
679  * response-ip actions.
680  * Note that this function distinguishes error conditions from "success but
681  * not overridden".  This is because we want to avoid accidentally applying
682  * the "no data" action in case of error.
683  * @param action: action to apply
684  * @param data: RRset to use for override
685  * @param qtype: original query type
686  * @param rep: original reply message
687  * @param rrset_id: the rrset ID in 'rep' to which the action should apply
688  * @param new_repp: see respip_rewrite_reply
689  * @param tag: if >= 0 the tag ID used to determine the action and data
690  * @param tag_datas: data corresponding to 'tag'.
691  * @param tag_datas_size: size of 'tag_datas'
692  * @param tagname: array of tag names, used for logging
693  * @param num_tags: size of 'tagname', used for logging
694  * @param redirect_rrsetp: ptr to redirect record
695  * @param region: region for building new reply
696  * @return 1 if overridden, 0 if not overridden, -1 on error.
697  */
698 static int
699 respip_data_answer(enum respip_action action,
700 	struct ub_packed_rrset_key* data,
701 	uint16_t qtype, const struct reply_info* rep,
702 	size_t rrset_id, struct reply_info** new_repp, int tag,
703 	struct config_strlist** tag_datas, size_t tag_datas_size,
704 	char* const* tagname, int num_tags,
705 	struct ub_packed_rrset_key** redirect_rrsetp, struct regional* region)
706 {
707 	struct ub_packed_rrset_key* rp = data;
708 	struct reply_info* new_rep;
709 	*redirect_rrsetp = NULL;
710 
711 	if(action == respip_redirect && tag != -1 &&
712 		(size_t)tag<tag_datas_size && tag_datas[tag]) {
713 		struct query_info dataqinfo;
714 		struct ub_packed_rrset_key r;
715 
716 		/* Extract parameters of the original answer rrset that can be
717 		 * rewritten below, in the form of query_info.  Note that these
718 		 * can be different from the info of the original query if the
719 		 * rrset is a CNAME target.*/
720 		memset(&dataqinfo, 0, sizeof(dataqinfo));
721 		dataqinfo.qname = rep->rrsets[rrset_id]->rk.dname;
722 		dataqinfo.qname_len = rep->rrsets[rrset_id]->rk.dname_len;
723 		dataqinfo.qtype = ntohs(rep->rrsets[rrset_id]->rk.type);
724 		dataqinfo.qclass = ntohs(rep->rrsets[rrset_id]->rk.rrset_class);
725 
726 		memset(&r, 0, sizeof(r));
727 		if(local_data_find_tag_datas(&dataqinfo, tag_datas[tag], &r,
728 			region)) {
729 			verbose(VERB_ALGO,
730 				"response-ip redirect with tag data [%d] %s",
731 				tag, (tag<num_tags?tagname[tag]:"null"));
732 			/* use copy_rrset() to 'normalize' memory layout */
733 			rp = copy_rrset(&r, region);
734 			if(!rp)
735 				return -1;
736 		}
737 	}
738 	if(!rp)
739 		return 0;
740 
741 	/* If we are using response-ip-data, we need to make a copy of rrset
742 	 * to replace the rrset's dname.  Note that, unlike local data, we
743 	 * rename the dname for other actions than redirect.  This is because
744 	 * response-ip-data isn't associated to any specific name. */
745 	if(rp == data) {
746 		rp = copy_rrset(rp, region);
747 		if(!rp)
748 			return -1;
749 		rp->rk.dname = rep->rrsets[rrset_id]->rk.dname;
750 		rp->rk.dname_len = rep->rrsets[rrset_id]->rk.dname_len;
751 	}
752 
753 	/* Build a new reply with redirect rrset.  We keep any preceding CNAMEs
754 	 * and replace the address rrset that triggers the action.  If it's
755 	 * type ANY query, however, no other answer records should be kept
756 	 * (note that it can't be a CNAME chain in this case due to
757 	 * sanitizing). */
758 	if(qtype == LDNS_RR_TYPE_ANY)
759 		rrset_id = 0;
760 	new_rep = make_new_reply_info(rep, region, rrset_id + 1, rrset_id);
761 	if(!new_rep)
762 		return -1;
763 	rp->rk.flags |= PACKED_RRSET_FIXEDTTL; /* avoid adjusting TTL */
764 	new_rep->rrsets[rrset_id] = rp;
765 
766 	*redirect_rrsetp = rp;
767 	*new_repp = new_rep;
768 	return 1;
769 }
770 
771 /**
772  * apply response ip action in case where no action data is provided.
773  * this is similar to localzone.c:lz_zone_answer() but simplified due to
774  * the characteristics of response ip:
775  * - 'deny' variants will be handled at the caller side
776  * - no specific processing for 'transparent' variants: unlike local zones,
777  *   there is no such a case of 'no data but name existing'.  so all variants
778  *   just mean 'transparent if no data'.
779  * @param qtype: query type
780  * @param action: found action
781  * @param rep:
782  * @param new_repp
783  * @param rrset_id
784  * @param region: region for building new reply
785  * @return 1 on success, 0 on error.
786  */
787 static int
788 respip_nodata_answer(uint16_t qtype, enum respip_action action,
789 	const struct reply_info *rep, size_t rrset_id,
790 	struct reply_info** new_repp, struct regional* region)
791 {
792 	struct reply_info* new_rep;
793 
794 	if(action == respip_refuse || action == respip_always_refuse) {
795 		new_rep = make_new_reply_info(rep, region, 0, 0);
796 		if(!new_rep)
797 			return 0;
798 		FLAGS_SET_RCODE(new_rep->flags, LDNS_RCODE_REFUSED);
799 		*new_repp = new_rep;
800 		return 1;
801 	} else if(action == respip_static || action == respip_redirect ||
802 		action == respip_always_nxdomain ||
803 		action == respip_always_nodata ||
804 		action == respip_inform_redirect) {
805 		/* Since we don't know about other types of the owner name,
806 		 * we generally return NOERROR/NODATA unless an NXDOMAIN action
807 		 * is explicitly specified. */
808 		int rcode = (action == respip_always_nxdomain)?
809 			LDNS_RCODE_NXDOMAIN:LDNS_RCODE_NOERROR;
810 
811 		/* We should empty the answer section except for any preceding
812 		 * CNAMEs (in that case rrset_id > 0).  Type-ANY case is
813 		 * special as noted in respip_data_answer(). */
814 		if(qtype == LDNS_RR_TYPE_ANY)
815 			rrset_id = 0;
816 		new_rep = make_new_reply_info(rep, region, rrset_id, rrset_id);
817 		if(!new_rep)
818 			return 0;
819 		FLAGS_SET_RCODE(new_rep->flags, rcode);
820 		*new_repp = new_rep;
821 		return 1;
822 	}
823 
824 	return 1;
825 }
826 
827 /** Populate action info structure with the results of response-ip action
828  *  processing, iff as the result of response-ip processing we are actually
829  *  taking some action. Only action is set if action_only is true.
830  *  Returns true on success, false on failure.
831  */
832 static int
833 populate_action_info(struct respip_action_info* actinfo,
834 	enum respip_action action, const struct resp_addr* raddr,
835 	const struct ub_packed_rrset_key* ATTR_UNUSED(rrset),
836 	int ATTR_UNUSED(tag), const struct respip_set* ATTR_UNUSED(ipset),
837 	int ATTR_UNUSED(action_only), struct regional* region, int rpz_used,
838 	int rpz_log, char* log_name, int rpz_cname_override)
839 {
840 	if(action == respip_none || !raddr)
841 		return 1;
842 	actinfo->action = action;
843 	actinfo->rpz_used = rpz_used;
844 	actinfo->rpz_log = rpz_log;
845 	actinfo->log_name = log_name;
846 	actinfo->rpz_cname_override = rpz_cname_override;
847 
848 	/* for inform variants, make a copy of the matched address block for
849 	 * later logging.  We make a copy to proactively avoid disruption if
850 	 *  and when we allow a dynamic update to the respip tree. */
851 	if(action == respip_inform || action == respip_inform_deny ||
852 		rpz_used) {
853 		struct respip_addr_info* a =
854 			regional_alloc_zero(region, sizeof(*a));
855 		if(!a) {
856 			log_err("out of memory");
857 			return 0;
858 		}
859 		a->addr = raddr->node.addr;
860 		a->addrlen = raddr->node.addrlen;
861 		a->net = raddr->node.net;
862 		actinfo->addrinfo = a;
863 	}
864 
865 	return 1;
866 }
867 
868 static int
869 respip_use_rpz(struct resp_addr* raddr, struct rpz* r,
870 	enum respip_action* action,
871 	struct ub_packed_rrset_key** data, int* rpz_log, char** log_name,
872 	int* rpz_cname_override, struct regional* region, int* is_rpz)
873 {
874 	if(r->action_override == RPZ_DISABLED_ACTION) {
875 		*is_rpz = 0;
876 		return 1;
877 	}
878 	else if(r->action_override == RPZ_NO_OVERRIDE_ACTION)
879 		*action = raddr->action;
880 	else
881 		*action = rpz_action_to_respip_action(r->action_override);
882 	if(r->action_override == RPZ_CNAME_OVERRIDE_ACTION &&
883 		r->cname_override) {
884 		*data = r->cname_override;
885 		*rpz_cname_override = 1;
886 	}
887 	*rpz_log = r->log;
888 	if(r->log_name)
889 		if(!(*log_name = regional_strdup(region, r->log_name)))
890 			return 0;
891 	*is_rpz = 1;
892 	return 1;
893 }
894 
895 int
896 respip_rewrite_reply(const struct query_info* qinfo,
897 	const struct respip_client_info* cinfo, const struct reply_info* rep,
898 	struct reply_info** new_repp, struct respip_action_info* actinfo,
899 	struct ub_packed_rrset_key** alias_rrset, int search_only,
900 	struct regional* region, struct auth_zones* az)
901 {
902 	const uint8_t* ctaglist;
903 	size_t ctaglen;
904 	const uint8_t* tag_actions;
905 	size_t tag_actions_size;
906 	struct config_strlist** tag_datas;
907 	size_t tag_datas_size;
908 	struct view* view = NULL;
909 	struct respip_set* ipset = NULL;
910 	size_t rrset_id = 0;
911 	enum respip_action action = respip_none;
912 	int tag = -1;
913 	struct resp_addr* raddr = NULL;
914 	int ret = 1;
915 	struct ub_packed_rrset_key* redirect_rrset = NULL;
916 	struct rpz* r;
917 	struct auth_zone* a = NULL;
918 	struct ub_packed_rrset_key* data = NULL;
919 	int rpz_used = 0;
920 	int rpz_log = 0;
921 	int rpz_cname_override = 0;
922 	char* log_name = NULL;
923 
924 	if(!cinfo)
925 		goto done;
926 	ctaglist = cinfo->taglist;
927 	ctaglen = cinfo->taglen;
928 	tag_actions = cinfo->tag_actions;
929 	tag_actions_size = cinfo->tag_actions_size;
930 	tag_datas = cinfo->tag_datas;
931 	tag_datas_size = cinfo->tag_datas_size;
932 	view = cinfo->view;
933 	ipset = cinfo->respip_set;
934 
935 	log_assert(ipset);
936 
937 	/** Try to use response-ip config from the view first; use
938 	  * global response-ip config if we don't have the view or we don't
939 	  * have the matching per-view config (and the view allows the use
940 	  * of global data in this case).
941 	  * Note that we lock the view even if we only use view members that
942 	  * currently don't change after creation.  This is for safety for
943 	  * future possible changes as the view documentation seems to expect
944 	  * any of its member can change in the view's lifetime.
945 	  * Note also that we assume 'view' is valid in this function, which
946 	  * should be safe (see unbound bug #1191) */
947 	if(view) {
948 		lock_rw_rdlock(&view->lock);
949 		if(view->respip_set) {
950 			if((raddr = respip_addr_lookup(rep,
951 				view->respip_set, &rrset_id))) {
952 				/** for per-view respip directives the action
953 				 * can only be direct (i.e. not tag-based) */
954 				action = raddr->action;
955 			}
956 		}
957 		if(!raddr && !view->isfirst)
958 			goto done;
959 		if(!raddr && view->isfirst) {
960 			lock_rw_unlock(&view->lock);
961 			view = NULL;
962 		}
963 	}
964 	if(!raddr && (raddr = respip_addr_lookup(rep, ipset,
965 		&rrset_id))) {
966 		action = (enum respip_action)local_data_find_tag_action(
967 			raddr->taglist, raddr->taglen, ctaglist, ctaglen,
968 			tag_actions, tag_actions_size,
969 			(enum localzone_type)raddr->action, &tag,
970 			ipset->tagname, ipset->num_tags);
971 	}
972 	lock_rw_rdlock(&az->rpz_lock);
973 	for(a = az->rpz_first; a && !raddr; a = a->rpz_az_next) {
974 		lock_rw_rdlock(&a->lock);
975 		r = a->rpz;
976 		if(!r->taglist || taglist_intersect(r->taglist,
977 			r->taglistlen, ctaglist, ctaglen)) {
978 			if((raddr = respip_addr_lookup(rep,
979 				r->respip_set, &rrset_id))) {
980 				if(!respip_use_rpz(raddr, r, &action, &data,
981 					&rpz_log, &log_name, &rpz_cname_override,
982 					region, &rpz_used)) {
983 					log_err("out of memory");
984 					lock_rw_unlock(&raddr->lock);
985 					lock_rw_unlock(&a->lock);
986 					lock_rw_unlock(&az->rpz_lock);
987 					return 0;
988 				}
989 				if(rpz_used) {
990 					/* break to make sure 'a' stays pointed
991 					 * to used auth_zone, and keeps lock */
992 					break;
993 				}
994 				lock_rw_unlock(&raddr->lock);
995 				raddr = NULL;
996 				actinfo->rpz_disabled++;
997 			}
998 		}
999 		lock_rw_unlock(&a->lock);
1000 	}
1001 	lock_rw_unlock(&az->rpz_lock);
1002 	if(raddr && !search_only) {
1003 		int result = 0;
1004 
1005 		/* first, see if we have response-ip or tag action for the
1006 		 * action except for 'always' variants. */
1007 		if(action != respip_always_refuse
1008 			&& action != respip_always_transparent
1009 			&& action != respip_always_nxdomain
1010 			&& action != respip_always_nodata
1011 			&& action != respip_always_deny
1012 			&& (result = respip_data_answer(action,
1013 			(data) ? data : raddr->data, qinfo->qtype, rep,
1014 			rrset_id, new_repp, tag, tag_datas, tag_datas_size,
1015 			ipset->tagname, ipset->num_tags, &redirect_rrset,
1016 			region)) < 0) {
1017 			ret = 0;
1018 			goto done;
1019 		}
1020 
1021 		/* if no action data applied, take action specific to the
1022 		 * action without data. */
1023 		if(!result && !respip_nodata_answer(qinfo->qtype, action, rep,
1024 			rrset_id, new_repp, region)) {
1025 			ret = 0;
1026 			goto done;
1027 		}
1028 	}
1029   done:
1030 	if(view) {
1031 		lock_rw_unlock(&view->lock);
1032 	}
1033 	if(ret) {
1034 		/* If we're redirecting the original answer to a
1035 		 * CNAME, record the CNAME rrset so the caller can take
1036 		 * the appropriate action.  Note that we don't check the
1037 		 * action type; it should normally be 'redirect', but it
1038 		 * can be of other type when a data-dependent tag action
1039 		 * uses redirect response-ip data.
1040 		 */
1041 		if(redirect_rrset &&
1042 			redirect_rrset->rk.type == ntohs(LDNS_RR_TYPE_CNAME) &&
1043 			qinfo->qtype != LDNS_RR_TYPE_ANY)
1044 			*alias_rrset = redirect_rrset;
1045 		/* on success, populate respip result structure */
1046 		ret = populate_action_info(actinfo, action, raddr,
1047 			redirect_rrset, tag, ipset, search_only, region,
1048 				rpz_used, rpz_log, log_name, rpz_cname_override);
1049 	}
1050 	if(raddr) {
1051 		lock_rw_unlock(&raddr->lock);
1052 	}
1053 	if(rpz_used) {
1054 		lock_rw_unlock(&a->lock);
1055 	}
1056 	return ret;
1057 }
1058 
1059 static int
1060 generate_cname_request(struct module_qstate* qstate,
1061 	struct ub_packed_rrset_key* alias_rrset)
1062 {
1063 	struct module_qstate* subq = NULL;
1064 	struct query_info subqi;
1065 
1066 	memset(&subqi, 0, sizeof(subqi));
1067 	get_cname_target(alias_rrset, &subqi.qname, &subqi.qname_len);
1068 	if(!subqi.qname)
1069 		return 0;    /* unexpected: not a valid CNAME RDATA */
1070 	subqi.qtype = qstate->qinfo.qtype;
1071 	subqi.qclass = qstate->qinfo.qclass;
1072 	fptr_ok(fptr_whitelist_modenv_attach_sub(qstate->env->attach_sub));
1073 	return (*qstate->env->attach_sub)(qstate, &subqi, BIT_RD, 0, 0, &subq);
1074 }
1075 
1076 void
1077 respip_operate(struct module_qstate* qstate, enum module_ev event, int id,
1078 	struct outbound_entry* outbound)
1079 {
1080 	struct respip_qstate* rq = (struct respip_qstate*)qstate->minfo[id];
1081 
1082 	log_query_info(VERB_QUERY, "respip operate: query", &qstate->qinfo);
1083 	(void)outbound;
1084 
1085 	if(event == module_event_new || event == module_event_pass) {
1086 		if(!rq) {
1087 			rq = regional_alloc_zero(qstate->region, sizeof(*rq));
1088 			if(!rq)
1089 				goto servfail;
1090 			rq->state = RESPIP_INIT;
1091 			qstate->minfo[id] = rq;
1092 		}
1093 		if(rq->state == RESPIP_SUBQUERY_FINISHED) {
1094 			qstate->ext_state[id] = module_finished;
1095 			return;
1096 		}
1097 		verbose(VERB_ALGO, "respip: pass to next module");
1098 		qstate->ext_state[id] = module_wait_module;
1099 	} else if(event == module_event_moddone) {
1100 		/* If the reply may be subject to response-ip rewriting
1101 		 * according to the query type, check the actions.  If a
1102 		 * rewrite is necessary, we'll replace the reply in qstate
1103 		 * with the new one. */
1104 		enum module_ext_state next_state = module_finished;
1105 
1106 		if((qstate->qinfo.qtype == LDNS_RR_TYPE_A ||
1107 			qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA ||
1108 			qstate->qinfo.qtype == LDNS_RR_TYPE_ANY) &&
1109 			qstate->return_msg && qstate->return_msg->rep) {
1110 			struct reply_info* new_rep = qstate->return_msg->rep;
1111 			struct ub_packed_rrset_key* alias_rrset = NULL;
1112 			struct respip_action_info actinfo = {0, 0, 0, 0, NULL, 0, NULL};
1113 			actinfo.action = respip_none;
1114 
1115 			if(!respip_rewrite_reply(&qstate->qinfo,
1116 				qstate->client_info, qstate->return_msg->rep,
1117 				&new_rep, &actinfo, &alias_rrset, 0,
1118 				qstate->region, qstate->env->auth_zones)) {
1119 				goto servfail;
1120 			}
1121 			if(actinfo.action != respip_none) {
1122 				/* save action info for logging on a
1123 				 * per-front-end-query basis */
1124 				if(!(qstate->respip_action_info =
1125 					regional_alloc_init(qstate->region,
1126 						&actinfo, sizeof(actinfo))))
1127 				{
1128 					log_err("out of memory");
1129 					goto servfail;
1130 				}
1131 			} else {
1132 				qstate->respip_action_info = NULL;
1133 			}
1134 			if (actinfo.action == respip_always_deny ||
1135 				(new_rep == qstate->return_msg->rep &&
1136 				(actinfo.action == respip_deny ||
1137 				actinfo.action == respip_inform_deny))) {
1138 				/* for deny-variant actions (unless response-ip
1139 				 * data is applied), mark the query state so
1140 				 * the response will be dropped for all
1141 				 * clients. */
1142 				qstate->is_drop = 1;
1143 			} else if(alias_rrset) {
1144 				if(!generate_cname_request(qstate, alias_rrset))
1145 					goto servfail;
1146 				next_state = module_wait_subquery;
1147 			}
1148 			qstate->return_msg->rep = new_rep;
1149 		}
1150 		qstate->ext_state[id] = next_state;
1151 	} else
1152 		qstate->ext_state[id] = module_finished;
1153 
1154 	return;
1155 
1156   servfail:
1157 	qstate->return_rcode = LDNS_RCODE_SERVFAIL;
1158 	qstate->return_msg = NULL;
1159 }
1160 
1161 int
1162 respip_merge_cname(struct reply_info* base_rep,
1163 	const struct query_info* qinfo, const struct reply_info* tgt_rep,
1164 	const struct respip_client_info* cinfo, int must_validate,
1165 	struct reply_info** new_repp, struct regional* region,
1166 	struct auth_zones* az)
1167 {
1168 	struct reply_info* new_rep;
1169 	struct reply_info* tmp_rep = NULL; /* just a placeholder */
1170 	struct ub_packed_rrset_key* alias_rrset = NULL; /* ditto */
1171 	uint16_t tgt_rcode;
1172 	size_t i, j;
1173 	struct respip_action_info actinfo = {0, 0, 0, 0, NULL, 0, NULL};
1174 	actinfo.action = respip_none;
1175 
1176 	/* If the query for the CNAME target would result in an unusual rcode,
1177 	 * we generally translate it as a failure for the base query
1178 	 * (which would then be translated into SERVFAIL).  The only exception
1179 	 * is NXDOMAIN and YXDOMAIN, which are passed to the end client(s).
1180 	 * The YXDOMAIN case would be rare but still possible (when
1181 	 * DNSSEC-validated DNAME has been cached but synthesizing CNAME
1182 	 * can't be generated due to length limitation) */
1183 	tgt_rcode = FLAGS_GET_RCODE(tgt_rep->flags);
1184 	if((tgt_rcode != LDNS_RCODE_NOERROR &&
1185 		tgt_rcode != LDNS_RCODE_NXDOMAIN &&
1186 		tgt_rcode != LDNS_RCODE_YXDOMAIN) ||
1187 		(must_validate && tgt_rep->security <= sec_status_bogus)) {
1188 		return 0;
1189 	}
1190 
1191 	/* see if the target reply would be subject to a response-ip action. */
1192 	if(!respip_rewrite_reply(qinfo, cinfo, tgt_rep, &tmp_rep, &actinfo,
1193 		&alias_rrset, 1, region, az))
1194 		return 0;
1195 	if(actinfo.action != respip_none) {
1196 		log_info("CNAME target of redirect response-ip action would "
1197 			"be subject to response-ip action, too; stripped");
1198 		*new_repp = base_rep;
1199 		return 1;
1200 	}
1201 
1202 	/* Append target reply to the base.  Since we cannot assume
1203 	 * tgt_rep->rrsets is valid throughout the lifetime of new_rep
1204 	 * or it can be safely shared by multiple threads, we need to make a
1205 	 * deep copy. */
1206 	new_rep = make_new_reply_info(base_rep, region,
1207 		base_rep->an_numrrsets + tgt_rep->an_numrrsets,
1208 		base_rep->an_numrrsets);
1209 	if(!new_rep)
1210 		return 0;
1211 	for(i=0,j=base_rep->an_numrrsets; i<tgt_rep->an_numrrsets; i++,j++) {
1212 		new_rep->rrsets[j] = copy_rrset(tgt_rep->rrsets[i], region);
1213 		if(!new_rep->rrsets[j])
1214 			return 0;
1215 	}
1216 
1217 	FLAGS_SET_RCODE(new_rep->flags, tgt_rcode);
1218 	*new_repp = new_rep;
1219 	return 1;
1220 }
1221 
1222 void
1223 respip_inform_super(struct module_qstate* qstate, int id,
1224 	struct module_qstate* super)
1225 {
1226 	struct respip_qstate* rq = (struct respip_qstate*)super->minfo[id];
1227 	struct reply_info* new_rep = NULL;
1228 
1229 	rq->state = RESPIP_SUBQUERY_FINISHED;
1230 
1231 	/* respip subquery should have always been created with a valid reply
1232 	 * in super. */
1233 	log_assert(super->return_msg && super->return_msg->rep);
1234 
1235 	/* return_msg can be NULL when, e.g., the sub query resulted in
1236 	 * SERVFAIL, in which case we regard it as a failure of the original
1237 	 * query.  Other checks are probably redundant, but we check them
1238 	 * for safety. */
1239 	if(!qstate->return_msg || !qstate->return_msg->rep ||
1240 		qstate->return_rcode != LDNS_RCODE_NOERROR)
1241 		goto fail;
1242 
1243 	if(!respip_merge_cname(super->return_msg->rep, &qstate->qinfo,
1244 		qstate->return_msg->rep, super->client_info,
1245 		super->env->need_to_validate, &new_rep, super->region,
1246 		qstate->env->auth_zones))
1247 		goto fail;
1248 	super->return_msg->rep = new_rep;
1249 	return;
1250 
1251   fail:
1252 	super->return_rcode = LDNS_RCODE_SERVFAIL;
1253 	super->return_msg = NULL;
1254 	return;
1255 }
1256 
1257 void
1258 respip_clear(struct module_qstate* qstate, int id)
1259 {
1260 	qstate->minfo[id] = NULL;
1261 }
1262 
1263 size_t
1264 respip_get_mem(struct module_env* env, int id)
1265 {
1266 	(void)env;
1267 	(void)id;
1268 	return 0;
1269 }
1270 
1271 /**
1272  * The response-ip function block
1273  */
1274 static struct module_func_block respip_block = {
1275 	"respip",
1276 	&respip_init, &respip_deinit, &respip_operate, &respip_inform_super,
1277 	&respip_clear, &respip_get_mem
1278 };
1279 
1280 struct module_func_block*
1281 respip_get_funcblock(void)
1282 {
1283 	return &respip_block;
1284 }
1285 
1286 enum respip_action
1287 resp_addr_get_action(const struct resp_addr* addr)
1288 {
1289 	return addr ? addr->action : respip_none;
1290 }
1291 
1292 struct ub_packed_rrset_key*
1293 resp_addr_get_rrset(struct resp_addr* addr)
1294 {
1295 	return addr ? addr->data : NULL;
1296 }
1297 
1298 int
1299 respip_set_is_empty(const struct respip_set* set)
1300 {
1301 	return set ? set->ip_tree.count == 0 : 1;
1302 }
1303 
1304 void
1305 respip_inform_print(struct respip_action_info* respip_actinfo, uint8_t* qname,
1306 	uint16_t qtype, uint16_t qclass, struct local_rrset* local_alias,
1307 	struct comm_reply* repinfo)
1308 {
1309 	char srcip[128], respip[128], txt[512];
1310 	unsigned port;
1311 	struct respip_addr_info* respip_addr = respip_actinfo->addrinfo;
1312 	size_t txtlen = 0;
1313 	const char* actionstr = NULL;
1314 
1315 	if(local_alias)
1316 		qname = local_alias->rrset->rk.dname;
1317 	port = (unsigned)((repinfo->addr.ss_family == AF_INET) ?
1318 		ntohs(((struct sockaddr_in*)&repinfo->addr)->sin_port) :
1319 		ntohs(((struct sockaddr_in6*)&repinfo->addr)->sin6_port));
1320 	addr_to_str(&repinfo->addr, repinfo->addrlen, srcip, sizeof(srcip));
1321 	addr_to_str(&respip_addr->addr, respip_addr->addrlen,
1322 		respip, sizeof(respip));
1323 	if(respip_actinfo->rpz_log) {
1324 		txtlen += snprintf(txt+txtlen, sizeof(txt)-txtlen, "%s",
1325 			"RPZ applied ");
1326 		if(respip_actinfo->rpz_cname_override)
1327 			actionstr = rpz_action_to_string(
1328 				RPZ_CNAME_OVERRIDE_ACTION);
1329 		else
1330 			actionstr = rpz_action_to_string(
1331 				respip_action_to_rpz_action(
1332 					respip_actinfo->action));
1333 	}
1334 	if(respip_actinfo->log_name) {
1335 		txtlen += snprintf(txt+txtlen, sizeof(txt)-txtlen,
1336 			"[%s] ", respip_actinfo->log_name);
1337 	}
1338 	snprintf(txt+txtlen, sizeof(txt)-txtlen,
1339 		"%s/%d %s %s@%u", respip, respip_addr->net,
1340 		(actionstr) ? actionstr : "inform", srcip, port);
1341 	log_nametypeclass(NO_VERBOSE, txt, qname, qtype, qclass);
1342 }
1343