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