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