1 /* 2 * daemon/worker.c - worker that handles a pending list of requests. 3 * 4 * Copyright (c) 2007, NLnet Labs. All rights reserved. 5 * 6 * This software is open source. 7 * 8 * Redistribution and use in source and binary forms, with or without 9 * modification, are permitted provided that the following conditions 10 * are met: 11 * 12 * Redistributions of source code must retain the above copyright notice, 13 * this list of conditions and the following disclaimer. 14 * 15 * Redistributions in binary form must reproduce the above copyright notice, 16 * this list of conditions and the following disclaimer in the documentation 17 * and/or other materials provided with the distribution. 18 * 19 * Neither the name of the NLNET LABS nor the names of its contributors may 20 * be used to endorse or promote products derived from this software without 21 * specific prior written permission. 22 * 23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 24 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 25 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 26 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 27 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 28 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 29 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 30 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 31 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 32 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 33 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 */ 35 36 /** 37 * \file 38 * 39 * This file implements the worker that handles callbacks on events, for 40 * pending requests. 41 */ 42 #include "config.h" 43 #include "util/log.h" 44 #include "util/net_help.h" 45 #include "util/random.h" 46 #include "daemon/worker.h" 47 #include "daemon/daemon.h" 48 #include "daemon/remote.h" 49 #include "daemon/acl_list.h" 50 #include "util/netevent.h" 51 #include "util/config_file.h" 52 #include "util/module.h" 53 #include "util/regional.h" 54 #include "util/storage/slabhash.h" 55 #include "services/listen_dnsport.h" 56 #include "services/outside_network.h" 57 #include "services/outbound_list.h" 58 #include "services/cache/rrset.h" 59 #include "services/cache/infra.h" 60 #include "services/cache/dns.h" 61 #include "services/authzone.h" 62 #include "services/mesh.h" 63 #include "services/localzone.h" 64 #include "services/rpz.h" 65 #include "util/data/msgparse.h" 66 #include "util/data/msgencode.h" 67 #include "util/data/dname.h" 68 #include "util/fptr_wlist.h" 69 #include "util/tube.h" 70 #include "util/edns.h" 71 #include "iterator/iter_fwd.h" 72 #include "iterator/iter_hints.h" 73 #include "iterator/iter_utils.h" 74 #include "validator/autotrust.h" 75 #include "validator/val_anchor.h" 76 #include "respip/respip.h" 77 #include "libunbound/context.h" 78 #include "libunbound/libworker.h" 79 #include "sldns/sbuffer.h" 80 #include "sldns/wire2str.h" 81 #include "util/shm_side/shm_main.h" 82 #include "dnscrypt/dnscrypt.h" 83 #include "dnstap/dtstream.h" 84 85 #ifdef HAVE_SYS_TYPES_H 86 # include <sys/types.h> 87 #endif 88 #ifdef HAVE_NETDB_H 89 #include <netdb.h> 90 #endif 91 #include <signal.h> 92 #ifdef UB_ON_WINDOWS 93 #include "winrc/win_svc.h" 94 #endif 95 96 /** Size of an UDP datagram */ 97 #define NORMAL_UDP_SIZE 512 /* bytes */ 98 /** ratelimit for error responses */ 99 #define ERROR_RATELIMIT 100 /* qps */ 100 101 /** 102 * seconds to add to prefetch leeway. This is a TTL that expires old rrsets 103 * earlier than they should in order to put the new update into the cache. 104 * This additional value is to make sure that if not all TTLs are equal in 105 * the message to be updated(and replaced), that rrsets with up to this much 106 * extra TTL are also replaced. This means that the resulting new message 107 * will have (most likely) this TTL at least, avoiding very small 'split 108 * second' TTLs due to operators choosing relative primes for TTLs (or so). 109 * Also has to be at least one to break ties (and overwrite cached entry). 110 */ 111 #define PREFETCH_EXPIRY_ADD 60 112 113 /** Report on memory usage by this thread and global */ 114 static void 115 worker_mem_report(struct worker* ATTR_UNUSED(worker), 116 struct serviced_query* ATTR_UNUSED(cur_serv)) 117 { 118 #ifdef UNBOUND_ALLOC_STATS 119 /* measure memory leakage */ 120 extern size_t unbound_mem_alloc, unbound_mem_freed; 121 /* debug func in validator module */ 122 size_t total, front, back, mesh, msg, rrset, infra, ac, superac; 123 size_t me, iter, val, anch; 124 int i; 125 #ifdef CLIENT_SUBNET 126 size_t subnet = 0; 127 #endif /* CLIENT_SUBNET */ 128 if(verbosity < VERB_ALGO) 129 return; 130 front = listen_get_mem(worker->front); 131 back = outnet_get_mem(worker->back); 132 msg = slabhash_get_mem(worker->env.msg_cache); 133 rrset = slabhash_get_mem(&worker->env.rrset_cache->table); 134 infra = infra_get_mem(worker->env.infra_cache); 135 mesh = mesh_get_mem(worker->env.mesh); 136 ac = alloc_get_mem(&worker->alloc); 137 superac = alloc_get_mem(&worker->daemon->superalloc); 138 anch = anchors_get_mem(worker->env.anchors); 139 iter = 0; 140 val = 0; 141 for(i=0; i<worker->env.mesh->mods.num; i++) { 142 fptr_ok(fptr_whitelist_mod_get_mem(worker->env.mesh-> 143 mods.mod[i]->get_mem)); 144 if(strcmp(worker->env.mesh->mods.mod[i]->name, "validator")==0) 145 val += (*worker->env.mesh->mods.mod[i]->get_mem) 146 (&worker->env, i); 147 #ifdef CLIENT_SUBNET 148 else if(strcmp(worker->env.mesh->mods.mod[i]->name, 149 "subnetcache")==0) 150 subnet += (*worker->env.mesh->mods.mod[i]->get_mem) 151 (&worker->env, i); 152 #endif /* CLIENT_SUBNET */ 153 else iter += (*worker->env.mesh->mods.mod[i]->get_mem) 154 (&worker->env, i); 155 } 156 me = sizeof(*worker) + sizeof(*worker->base) + sizeof(*worker->comsig) 157 + comm_point_get_mem(worker->cmd_com) 158 + sizeof(worker->rndstate) 159 + regional_get_mem(worker->scratchpad) 160 + sizeof(*worker->env.scratch_buffer) 161 + sldns_buffer_capacity(worker->env.scratch_buffer) 162 + forwards_get_mem(worker->env.fwds) 163 + hints_get_mem(worker->env.hints); 164 if(worker->thread_num == 0) 165 me += acl_list_get_mem(worker->daemon->acl); 166 if(cur_serv) { 167 me += serviced_get_mem(cur_serv); 168 } 169 total = front+back+mesh+msg+rrset+infra+iter+val+ac+superac+me; 170 #ifdef CLIENT_SUBNET 171 total += subnet; 172 log_info("Memory conditions: %u front=%u back=%u mesh=%u msg=%u " 173 "rrset=%u infra=%u iter=%u val=%u subnet=%u anchors=%u " 174 "alloccache=%u globalalloccache=%u me=%u", 175 (unsigned)total, (unsigned)front, (unsigned)back, 176 (unsigned)mesh, (unsigned)msg, (unsigned)rrset, (unsigned)infra, 177 (unsigned)iter, (unsigned)val, 178 (unsigned)subnet, (unsigned)anch, (unsigned)ac, 179 (unsigned)superac, (unsigned)me); 180 #else /* no CLIENT_SUBNET */ 181 log_info("Memory conditions: %u front=%u back=%u mesh=%u msg=%u " 182 "rrset=%u infra=%u iter=%u val=%u anchors=%u " 183 "alloccache=%u globalalloccache=%u me=%u", 184 (unsigned)total, (unsigned)front, (unsigned)back, 185 (unsigned)mesh, (unsigned)msg, (unsigned)rrset, 186 (unsigned)infra, (unsigned)iter, (unsigned)val, (unsigned)anch, 187 (unsigned)ac, (unsigned)superac, (unsigned)me); 188 #endif /* CLIENT_SUBNET */ 189 log_info("Total heap memory estimate: %u total-alloc: %u " 190 "total-free: %u", (unsigned)total, 191 (unsigned)unbound_mem_alloc, (unsigned)unbound_mem_freed); 192 #else /* no UNBOUND_ALLOC_STATS */ 193 size_t val = 0; 194 #ifdef CLIENT_SUBNET 195 size_t subnet = 0; 196 #endif /* CLIENT_SUBNET */ 197 int i; 198 if(verbosity < VERB_QUERY) 199 return; 200 for(i=0; i<worker->env.mesh->mods.num; i++) { 201 fptr_ok(fptr_whitelist_mod_get_mem(worker->env.mesh-> 202 mods.mod[i]->get_mem)); 203 if(strcmp(worker->env.mesh->mods.mod[i]->name, "validator")==0) 204 val += (*worker->env.mesh->mods.mod[i]->get_mem) 205 (&worker->env, i); 206 #ifdef CLIENT_SUBNET 207 else if(strcmp(worker->env.mesh->mods.mod[i]->name, 208 "subnetcache")==0) 209 subnet += (*worker->env.mesh->mods.mod[i]->get_mem) 210 (&worker->env, i); 211 #endif /* CLIENT_SUBNET */ 212 } 213 #ifdef CLIENT_SUBNET 214 verbose(VERB_QUERY, "cache memory msg=%u rrset=%u infra=%u val=%u " 215 "subnet=%u", 216 (unsigned)slabhash_get_mem(worker->env.msg_cache), 217 (unsigned)slabhash_get_mem(&worker->env.rrset_cache->table), 218 (unsigned)infra_get_mem(worker->env.infra_cache), 219 (unsigned)val, (unsigned)subnet); 220 #else /* no CLIENT_SUBNET */ 221 verbose(VERB_QUERY, "cache memory msg=%u rrset=%u infra=%u val=%u", 222 (unsigned)slabhash_get_mem(worker->env.msg_cache), 223 (unsigned)slabhash_get_mem(&worker->env.rrset_cache->table), 224 (unsigned)infra_get_mem(worker->env.infra_cache), 225 (unsigned)val); 226 #endif /* CLIENT_SUBNET */ 227 #endif /* UNBOUND_ALLOC_STATS */ 228 } 229 230 void 231 worker_send_cmd(struct worker* worker, enum worker_commands cmd) 232 { 233 uint32_t c = (uint32_t)htonl(cmd); 234 if(!tube_write_msg(worker->cmd, (uint8_t*)&c, sizeof(c), 0)) { 235 log_err("worker send cmd %d failed", (int)cmd); 236 } 237 } 238 239 int 240 worker_handle_service_reply(struct comm_point* c, void* arg, int error, 241 struct comm_reply* reply_info) 242 { 243 struct outbound_entry* e = (struct outbound_entry*)arg; 244 struct worker* worker = e->qstate->env->worker; 245 struct serviced_query *sq = e->qsent; 246 247 verbose(VERB_ALGO, "worker svcd callback for qstate %p", e->qstate); 248 if(error != 0) { 249 mesh_report_reply(worker->env.mesh, e, reply_info, error); 250 worker_mem_report(worker, sq); 251 return 0; 252 } 253 /* sanity check. */ 254 if(!LDNS_QR_WIRE(sldns_buffer_begin(c->buffer)) 255 || LDNS_OPCODE_WIRE(sldns_buffer_begin(c->buffer)) != 256 LDNS_PACKET_QUERY 257 || LDNS_QDCOUNT(sldns_buffer_begin(c->buffer)) > 1) { 258 /* error becomes timeout for the module as if this reply 259 * never arrived. */ 260 verbose(VERB_ALGO, "worker: bad reply handled as timeout"); 261 mesh_report_reply(worker->env.mesh, e, reply_info, 262 NETEVENT_TIMEOUT); 263 worker_mem_report(worker, sq); 264 return 0; 265 } 266 mesh_report_reply(worker->env.mesh, e, reply_info, NETEVENT_NOERROR); 267 worker_mem_report(worker, sq); 268 return 0; 269 } 270 271 /** ratelimit error replies 272 * @param worker: the worker struct with ratelimit counter 273 * @param err: error code that would be wanted. 274 * @return value of err if okay, or -1 if it should be discarded instead. 275 */ 276 static int 277 worker_err_ratelimit(struct worker* worker, int err) 278 { 279 if(worker->err_limit_time == *worker->env.now) { 280 /* see if limit is exceeded for this second */ 281 if(worker->err_limit_count++ > ERROR_RATELIMIT) 282 return -1; 283 } else { 284 /* new second, new limits */ 285 worker->err_limit_time = *worker->env.now; 286 worker->err_limit_count = 1; 287 } 288 return err; 289 } 290 291 /** check request sanity. 292 * @param pkt: the wire packet to examine for sanity. 293 * @param worker: parameters for checking. 294 * @return error code, 0 OK, or -1 discard. 295 */ 296 static int 297 worker_check_request(sldns_buffer* pkt, struct worker* worker) 298 { 299 if(sldns_buffer_limit(pkt) < LDNS_HEADER_SIZE) { 300 verbose(VERB_QUERY, "request too short, discarded"); 301 return -1; 302 } 303 if(sldns_buffer_limit(pkt) > NORMAL_UDP_SIZE && 304 worker->daemon->cfg->harden_large_queries) { 305 verbose(VERB_QUERY, "request too large, discarded"); 306 return -1; 307 } 308 if(LDNS_QR_WIRE(sldns_buffer_begin(pkt))) { 309 verbose(VERB_QUERY, "request has QR bit on, discarded"); 310 return -1; 311 } 312 if(LDNS_TC_WIRE(sldns_buffer_begin(pkt))) { 313 LDNS_TC_CLR(sldns_buffer_begin(pkt)); 314 verbose(VERB_QUERY, "request bad, has TC bit on"); 315 return worker_err_ratelimit(worker, LDNS_RCODE_FORMERR); 316 } 317 if(LDNS_OPCODE_WIRE(sldns_buffer_begin(pkt)) != LDNS_PACKET_QUERY && 318 LDNS_OPCODE_WIRE(sldns_buffer_begin(pkt)) != LDNS_PACKET_NOTIFY) { 319 verbose(VERB_QUERY, "request unknown opcode %d", 320 LDNS_OPCODE_WIRE(sldns_buffer_begin(pkt))); 321 return worker_err_ratelimit(worker, LDNS_RCODE_NOTIMPL); 322 } 323 if(LDNS_QDCOUNT(sldns_buffer_begin(pkt)) != 1) { 324 verbose(VERB_QUERY, "request wrong nr qd=%d", 325 LDNS_QDCOUNT(sldns_buffer_begin(pkt))); 326 return worker_err_ratelimit(worker, LDNS_RCODE_FORMERR); 327 } 328 if(LDNS_ANCOUNT(sldns_buffer_begin(pkt)) != 0 && 329 (LDNS_ANCOUNT(sldns_buffer_begin(pkt)) != 1 || 330 LDNS_OPCODE_WIRE(sldns_buffer_begin(pkt)) != LDNS_PACKET_NOTIFY)) { 331 verbose(VERB_QUERY, "request wrong nr an=%d", 332 LDNS_ANCOUNT(sldns_buffer_begin(pkt))); 333 return worker_err_ratelimit(worker, LDNS_RCODE_FORMERR); 334 } 335 if(LDNS_NSCOUNT(sldns_buffer_begin(pkt)) != 0) { 336 verbose(VERB_QUERY, "request wrong nr ns=%d", 337 LDNS_NSCOUNT(sldns_buffer_begin(pkt))); 338 return worker_err_ratelimit(worker, LDNS_RCODE_FORMERR); 339 } 340 if(LDNS_ARCOUNT(sldns_buffer_begin(pkt)) > 1) { 341 verbose(VERB_QUERY, "request wrong nr ar=%d", 342 LDNS_ARCOUNT(sldns_buffer_begin(pkt))); 343 return worker_err_ratelimit(worker, LDNS_RCODE_FORMERR); 344 } 345 return 0; 346 } 347 348 void 349 worker_handle_control_cmd(struct tube* ATTR_UNUSED(tube), uint8_t* msg, 350 size_t len, int error, void* arg) 351 { 352 struct worker* worker = (struct worker*)arg; 353 enum worker_commands cmd; 354 if(error != NETEVENT_NOERROR) { 355 free(msg); 356 if(error == NETEVENT_CLOSED) 357 comm_base_exit(worker->base); 358 else log_info("control event: %d", error); 359 return; 360 } 361 if(len != sizeof(uint32_t)) { 362 fatal_exit("bad control msg length %d", (int)len); 363 } 364 cmd = sldns_read_uint32(msg); 365 free(msg); 366 switch(cmd) { 367 case worker_cmd_quit: 368 verbose(VERB_ALGO, "got control cmd quit"); 369 comm_base_exit(worker->base); 370 break; 371 case worker_cmd_stats: 372 verbose(VERB_ALGO, "got control cmd stats"); 373 server_stats_reply(worker, 1); 374 break; 375 case worker_cmd_stats_noreset: 376 verbose(VERB_ALGO, "got control cmd stats_noreset"); 377 server_stats_reply(worker, 0); 378 break; 379 case worker_cmd_remote: 380 verbose(VERB_ALGO, "got control cmd remote"); 381 daemon_remote_exec(worker); 382 break; 383 default: 384 log_err("bad command %d", (int)cmd); 385 break; 386 } 387 } 388 389 /** check if a delegation is secure */ 390 static enum sec_status 391 check_delegation_secure(struct reply_info *rep) 392 { 393 /* return smallest security status */ 394 size_t i; 395 enum sec_status sec = sec_status_secure; 396 enum sec_status s; 397 size_t num = rep->an_numrrsets + rep->ns_numrrsets; 398 /* check if answer and authority are OK */ 399 for(i=0; i<num; i++) { 400 s = ((struct packed_rrset_data*)rep->rrsets[i]->entry.data) 401 ->security; 402 if(s < sec) 403 sec = s; 404 } 405 /* in additional, only unchecked triggers revalidation */ 406 for(i=num; i<rep->rrset_count; i++) { 407 s = ((struct packed_rrset_data*)rep->rrsets[i]->entry.data) 408 ->security; 409 if(s == sec_status_unchecked) 410 return s; 411 } 412 return sec; 413 } 414 415 /** remove nonsecure from a delegation referral additional section */ 416 static void 417 deleg_remove_nonsecure_additional(struct reply_info* rep) 418 { 419 /* we can simply edit it, since we are working in the scratch region */ 420 size_t i; 421 enum sec_status s; 422 423 for(i = rep->an_numrrsets+rep->ns_numrrsets; i<rep->rrset_count; i++) { 424 s = ((struct packed_rrset_data*)rep->rrsets[i]->entry.data) 425 ->security; 426 if(s != sec_status_secure) { 427 memmove(rep->rrsets+i, rep->rrsets+i+1, 428 sizeof(struct ub_packed_rrset_key*)* 429 (rep->rrset_count - i - 1)); 430 rep->ar_numrrsets--; 431 rep->rrset_count--; 432 i--; 433 } 434 } 435 } 436 437 /** answer nonrecursive query from the cache */ 438 static int 439 answer_norec_from_cache(struct worker* worker, struct query_info* qinfo, 440 uint16_t id, uint16_t flags, struct comm_reply* repinfo, 441 struct edns_data* edns) 442 { 443 /* for a nonrecursive query return either: 444 * o an error (servfail; we try to avoid this) 445 * o a delegation (closest we have; this routine tries that) 446 * o the answer (checked by answer_from_cache) 447 * 448 * So, grab a delegation from the rrset cache. 449 * Then check if it needs validation, if so, this routine fails, 450 * so that iterator can prime and validator can verify rrsets. 451 */ 452 uint16_t udpsize = edns->udp_size; 453 int secure = 0; 454 time_t timenow = *worker->env.now; 455 int must_validate = (!(flags&BIT_CD) || worker->env.cfg->ignore_cd) 456 && worker->env.need_to_validate; 457 struct dns_msg *msg = NULL; 458 struct delegpt *dp; 459 460 dp = dns_cache_find_delegation(&worker->env, qinfo->qname, 461 qinfo->qname_len, qinfo->qtype, qinfo->qclass, 462 worker->scratchpad, &msg, timenow); 463 if(!dp) { /* no delegation, need to reprime */ 464 return 0; 465 } 466 /* In case we have a local alias, copy it into the delegation message. 467 * Shallow copy should be fine, as we'll be done with msg in this 468 * function. */ 469 msg->qinfo.local_alias = qinfo->local_alias; 470 if(must_validate) { 471 switch(check_delegation_secure(msg->rep)) { 472 case sec_status_unchecked: 473 /* some rrsets have not been verified yet, go and 474 * let validator do that */ 475 return 0; 476 case sec_status_bogus: 477 case sec_status_secure_sentinel_fail: 478 /* some rrsets are bogus, reply servfail */ 479 edns->edns_version = EDNS_ADVERTISED_VERSION; 480 edns->udp_size = EDNS_ADVERTISED_SIZE; 481 edns->ext_rcode = 0; 482 edns->bits &= EDNS_DO; 483 if(!inplace_cb_reply_servfail_call(&worker->env, qinfo, NULL, 484 msg->rep, LDNS_RCODE_SERVFAIL, edns, repinfo, worker->scratchpad, 485 worker->env.now_tv)) 486 return 0; 487 error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL, 488 &msg->qinfo, id, flags, edns); 489 if(worker->stats.extended) { 490 worker->stats.ans_bogus++; 491 worker->stats.ans_rcode[LDNS_RCODE_SERVFAIL]++; 492 } 493 return 1; 494 case sec_status_secure: 495 /* all rrsets are secure */ 496 /* remove non-secure rrsets from the add. section*/ 497 if(worker->env.cfg->val_clean_additional) 498 deleg_remove_nonsecure_additional(msg->rep); 499 secure = 1; 500 break; 501 case sec_status_indeterminate: 502 case sec_status_insecure: 503 default: 504 /* not secure */ 505 secure = 0; 506 break; 507 } 508 } 509 /* return this delegation from the cache */ 510 edns->edns_version = EDNS_ADVERTISED_VERSION; 511 edns->udp_size = EDNS_ADVERTISED_SIZE; 512 edns->ext_rcode = 0; 513 edns->bits &= EDNS_DO; 514 if(!inplace_cb_reply_cache_call(&worker->env, qinfo, NULL, msg->rep, 515 (int)(flags&LDNS_RCODE_MASK), edns, repinfo, worker->scratchpad, 516 worker->env.now_tv)) 517 return 0; 518 msg->rep->flags |= BIT_QR|BIT_RA; 519 if(!reply_info_answer_encode(&msg->qinfo, msg->rep, id, flags, 520 repinfo->c->buffer, 0, 1, worker->scratchpad, 521 udpsize, edns, (int)(edns->bits & EDNS_DO), secure)) { 522 if(!inplace_cb_reply_servfail_call(&worker->env, qinfo, NULL, NULL, 523 LDNS_RCODE_SERVFAIL, edns, repinfo, worker->scratchpad, 524 worker->env.now_tv)) 525 edns->opt_list_inplace_cb_out = NULL; 526 error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL, 527 &msg->qinfo, id, flags, edns); 528 } 529 if(worker->stats.extended) { 530 if(secure) worker->stats.ans_secure++; 531 server_stats_insrcode(&worker->stats, repinfo->c->buffer); 532 } 533 return 1; 534 } 535 536 /** Apply, if applicable, a response IP action to a cached answer. 537 * If the answer is rewritten as a result of an action, '*encode_repp' will 538 * point to the reply info containing the modified answer. '*encode_repp' will 539 * be intact otherwise. 540 * It returns 1 on success, 0 otherwise. */ 541 static int 542 apply_respip_action(struct worker* worker, const struct query_info* qinfo, 543 struct respip_client_info* cinfo, struct reply_info* rep, 544 struct comm_reply* repinfo, struct ub_packed_rrset_key** alias_rrset, 545 struct reply_info** encode_repp, struct auth_zones* az) 546 { 547 struct respip_action_info actinfo = {0, 0, 0, 0, NULL, 0, NULL}; 548 actinfo.action = respip_none; 549 550 if(qinfo->qtype != LDNS_RR_TYPE_A && 551 qinfo->qtype != LDNS_RR_TYPE_AAAA && 552 qinfo->qtype != LDNS_RR_TYPE_ANY) 553 return 1; 554 555 if(!respip_rewrite_reply(qinfo, cinfo, rep, encode_repp, &actinfo, 556 alias_rrset, 0, worker->scratchpad, az)) 557 return 0; 558 559 /* xxx_deny actions mean dropping the reply, unless the original reply 560 * was redirected to response-ip data. */ 561 if((actinfo.action == respip_deny || 562 actinfo.action == respip_inform_deny) && 563 *encode_repp == rep) 564 *encode_repp = NULL; 565 566 /* If address info is returned, it means the action should be an 567 * 'inform' variant and the information should be logged. */ 568 if(actinfo.addrinfo) { 569 respip_inform_print(&actinfo, qinfo->qname, 570 qinfo->qtype, qinfo->qclass, qinfo->local_alias, 571 repinfo); 572 573 if(worker->stats.extended && actinfo.rpz_used) { 574 if(actinfo.rpz_disabled) 575 worker->stats.rpz_action[RPZ_DISABLED_ACTION]++; 576 if(actinfo.rpz_cname_override) 577 worker->stats.rpz_action[RPZ_CNAME_OVERRIDE_ACTION]++; 578 else 579 worker->stats.rpz_action[ 580 respip_action_to_rpz_action(actinfo.action)]++; 581 } 582 } 583 584 return 1; 585 } 586 587 /** answer query from the cache. 588 * Normally, the answer message will be built in repinfo->c->buffer; if the 589 * answer is supposed to be suppressed or the answer is supposed to be an 590 * incomplete CNAME chain, the buffer is explicitly cleared to signal the 591 * caller as such. In the latter case *partial_rep will point to the incomplete 592 * reply, and this function is (possibly) supposed to be called again with that 593 * *partial_rep value to complete the chain. In addition, if the query should 594 * be completely dropped, '*need_drop' will be set to 1. */ 595 static int 596 answer_from_cache(struct worker* worker, struct query_info* qinfo, 597 struct respip_client_info* cinfo, int* need_drop, int* is_expired_answer, 598 int* is_secure_answer, struct ub_packed_rrset_key** alias_rrset, 599 struct reply_info** partial_repp, 600 struct reply_info* rep, uint16_t id, uint16_t flags, 601 struct comm_reply* repinfo, struct edns_data* edns) 602 { 603 time_t timenow = *worker->env.now; 604 uint16_t udpsize = edns->udp_size; 605 struct reply_info* encode_rep = rep; 606 struct reply_info* partial_rep = *partial_repp; 607 int must_validate = (!(flags&BIT_CD) || worker->env.cfg->ignore_cd) 608 && worker->env.need_to_validate; 609 *partial_repp = NULL; /* avoid accidental further pass */ 610 611 /* Check TTL */ 612 if(rep->ttl < timenow) { 613 /* Check if we need to serve expired now */ 614 if(worker->env.cfg->serve_expired && 615 !worker->env.cfg->serve_expired_client_timeout) { 616 if(worker->env.cfg->serve_expired_ttl && 617 rep->serve_expired_ttl < timenow) 618 return 0; 619 if(!rrset_array_lock(rep->ref, rep->rrset_count, 0)) 620 return 0; 621 *is_expired_answer = 1; 622 } else { 623 /* the rrsets may have been updated in the meantime. 624 * we will refetch the message format from the 625 * authoritative server 626 */ 627 return 0; 628 } 629 } else { 630 if(!rrset_array_lock(rep->ref, rep->rrset_count, timenow)) 631 return 0; 632 } 633 /* locked and ids and ttls are OK. */ 634 635 /* check CNAME chain (if any) */ 636 if(rep->an_numrrsets > 0 && (rep->rrsets[0]->rk.type == 637 htons(LDNS_RR_TYPE_CNAME) || rep->rrsets[0]->rk.type == 638 htons(LDNS_RR_TYPE_DNAME))) { 639 if(!reply_check_cname_chain(qinfo, rep)) { 640 /* cname chain invalid, redo iterator steps */ 641 verbose(VERB_ALGO, "Cache reply: cname chain broken"); 642 goto bail_out; 643 } 644 } 645 /* check security status of the cached answer */ 646 if(must_validate && (rep->security == sec_status_bogus || 647 rep->security == sec_status_secure_sentinel_fail)) { 648 /* BAD cached */ 649 edns->edns_version = EDNS_ADVERTISED_VERSION; 650 edns->udp_size = EDNS_ADVERTISED_SIZE; 651 edns->ext_rcode = 0; 652 edns->bits &= EDNS_DO; 653 if(!inplace_cb_reply_servfail_call(&worker->env, qinfo, NULL, rep, 654 LDNS_RCODE_SERVFAIL, edns, repinfo, worker->scratchpad, 655 worker->env.now_tv)) 656 goto bail_out; 657 error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL, 658 qinfo, id, flags, edns); 659 rrset_array_unlock_touch(worker->env.rrset_cache, 660 worker->scratchpad, rep->ref, rep->rrset_count); 661 if(worker->stats.extended) { 662 worker->stats.ans_bogus ++; 663 worker->stats.ans_rcode[LDNS_RCODE_SERVFAIL] ++; 664 } 665 return 1; 666 } else if(rep->security == sec_status_unchecked && must_validate) { 667 verbose(VERB_ALGO, "Cache reply: unchecked entry needs " 668 "validation"); 669 goto bail_out; /* need to validate cache entry first */ 670 } else if(rep->security == sec_status_secure) { 671 if(reply_all_rrsets_secure(rep)) { 672 *is_secure_answer = 1; 673 } else { 674 if(must_validate) { 675 verbose(VERB_ALGO, "Cache reply: secure entry" 676 " changed status"); 677 goto bail_out; /* rrset changed, re-verify */ 678 } 679 *is_secure_answer = 0; 680 } 681 } else *is_secure_answer = 0; 682 683 edns->edns_version = EDNS_ADVERTISED_VERSION; 684 edns->udp_size = EDNS_ADVERTISED_SIZE; 685 edns->ext_rcode = 0; 686 edns->bits &= EDNS_DO; 687 if(!inplace_cb_reply_cache_call(&worker->env, qinfo, NULL, rep, 688 (int)(flags&LDNS_RCODE_MASK), edns, repinfo, worker->scratchpad, 689 worker->env.now_tv)) 690 goto bail_out; 691 *alias_rrset = NULL; /* avoid confusion if caller set it to non-NULL */ 692 if((worker->daemon->use_response_ip || worker->daemon->use_rpz) && 693 !partial_rep && !apply_respip_action(worker, qinfo, cinfo, rep, 694 repinfo, alias_rrset, 695 &encode_rep, worker->env.auth_zones)) { 696 goto bail_out; 697 } else if(partial_rep && 698 !respip_merge_cname(partial_rep, qinfo, rep, cinfo, 699 must_validate, &encode_rep, worker->scratchpad, 700 worker->env.auth_zones)) { 701 goto bail_out; 702 } 703 if(encode_rep != rep) { 704 /* if rewritten, it can't be considered "secure" */ 705 *is_secure_answer = 0; 706 } 707 if(!encode_rep || *alias_rrset) { 708 if(!encode_rep) 709 *need_drop = 1; 710 else { 711 /* If a partial CNAME chain is found, we first need to 712 * make a copy of the reply in the scratchpad so we 713 * can release the locks and lookup the cache again. */ 714 *partial_repp = reply_info_copy(encode_rep, NULL, 715 worker->scratchpad); 716 if(!*partial_repp) 717 goto bail_out; 718 } 719 } else if(!reply_info_answer_encode(qinfo, encode_rep, id, flags, 720 repinfo->c->buffer, timenow, 1, worker->scratchpad, 721 udpsize, edns, (int)(edns->bits & EDNS_DO), *is_secure_answer)) { 722 if(!inplace_cb_reply_servfail_call(&worker->env, qinfo, NULL, NULL, 723 LDNS_RCODE_SERVFAIL, edns, repinfo, worker->scratchpad, 724 worker->env.now_tv)) 725 edns->opt_list_inplace_cb_out = NULL; 726 error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL, 727 qinfo, id, flags, edns); 728 } 729 /* cannot send the reply right now, because blocking network syscall 730 * is bad while holding locks. */ 731 rrset_array_unlock_touch(worker->env.rrset_cache, worker->scratchpad, 732 rep->ref, rep->rrset_count); 733 /* go and return this buffer to the client */ 734 return 1; 735 736 bail_out: 737 rrset_array_unlock_touch(worker->env.rrset_cache, 738 worker->scratchpad, rep->ref, rep->rrset_count); 739 return 0; 740 } 741 742 /** Reply to client and perform prefetch to keep cache up to date. */ 743 static void 744 reply_and_prefetch(struct worker* worker, struct query_info* qinfo, 745 uint16_t flags, struct comm_reply* repinfo, time_t leeway, int noreply) 746 { 747 /* first send answer to client to keep its latency 748 * as small as a cachereply */ 749 if(!noreply) { 750 if(repinfo->c->tcp_req_info) { 751 sldns_buffer_copy( 752 repinfo->c->tcp_req_info->spool_buffer, 753 repinfo->c->buffer); 754 } 755 comm_point_send_reply(repinfo); 756 } 757 server_stats_prefetch(&worker->stats, worker); 758 759 /* create the prefetch in the mesh as a normal lookup without 760 * client addrs waiting, which has the cache blacklisted (to bypass 761 * the cache and go to the network for the data). */ 762 /* this (potentially) runs the mesh for the new query */ 763 mesh_new_prefetch(worker->env.mesh, qinfo, flags, leeway + 764 PREFETCH_EXPIRY_ADD); 765 } 766 767 /** 768 * Fill CH class answer into buffer. Keeps query. 769 * @param pkt: buffer 770 * @param str: string to put into text record (<255). 771 * array of strings, every string becomes a text record. 772 * @param num: number of strings in array. 773 * @param edns: edns reply information. 774 * @param worker: worker with scratch region. 775 * @param repinfo: reply information for a communication point. 776 */ 777 static void 778 chaos_replystr(sldns_buffer* pkt, char** str, int num, struct edns_data* edns, 779 struct worker* worker, struct comm_reply* repinfo) 780 { 781 int i; 782 unsigned int rd = LDNS_RD_WIRE(sldns_buffer_begin(pkt)); 783 unsigned int cd = LDNS_CD_WIRE(sldns_buffer_begin(pkt)); 784 size_t udpsize = edns->udp_size; 785 edns->edns_version = EDNS_ADVERTISED_VERSION; 786 edns->udp_size = EDNS_ADVERTISED_SIZE; 787 edns->bits &= EDNS_DO; 788 if(!inplace_cb_reply_local_call(&worker->env, NULL, NULL, NULL, 789 LDNS_RCODE_NOERROR, edns, repinfo, worker->scratchpad, 790 worker->env.now_tv)) 791 edns->opt_list_inplace_cb_out = NULL; 792 sldns_buffer_clear(pkt); 793 sldns_buffer_skip(pkt, (ssize_t)sizeof(uint16_t)); /* skip id */ 794 sldns_buffer_write_u16(pkt, (uint16_t)(BIT_QR|BIT_RA)); 795 if(rd) LDNS_RD_SET(sldns_buffer_begin(pkt)); 796 if(cd) LDNS_CD_SET(sldns_buffer_begin(pkt)); 797 sldns_buffer_write_u16(pkt, 1); /* qdcount */ 798 sldns_buffer_write_u16(pkt, (uint16_t)num); /* ancount */ 799 sldns_buffer_write_u16(pkt, 0); /* nscount */ 800 sldns_buffer_write_u16(pkt, 0); /* arcount */ 801 (void)query_dname_len(pkt); /* skip qname */ 802 sldns_buffer_skip(pkt, (ssize_t)sizeof(uint16_t)); /* skip qtype */ 803 sldns_buffer_skip(pkt, (ssize_t)sizeof(uint16_t)); /* skip qclass */ 804 for(i=0; i<num; i++) { 805 size_t len = strlen(str[i]); 806 if(len>255) len=255; /* cap size of TXT record */ 807 if(sldns_buffer_position(pkt)+2+2+2+4+2+1+len+ 808 calc_edns_field_size(edns) > udpsize) { 809 sldns_buffer_write_u16_at(pkt, 6, i); /* ANCOUNT */ 810 LDNS_TC_SET(sldns_buffer_begin(pkt)); 811 break; 812 } 813 sldns_buffer_write_u16(pkt, 0xc00c); /* compr ptr to query */ 814 sldns_buffer_write_u16(pkt, LDNS_RR_TYPE_TXT); 815 sldns_buffer_write_u16(pkt, LDNS_RR_CLASS_CH); 816 sldns_buffer_write_u32(pkt, 0); /* TTL */ 817 sldns_buffer_write_u16(pkt, sizeof(uint8_t) + len); 818 sldns_buffer_write_u8(pkt, len); 819 sldns_buffer_write(pkt, str[i], len); 820 } 821 sldns_buffer_flip(pkt); 822 if(sldns_buffer_capacity(pkt) >= 823 sldns_buffer_limit(pkt)+calc_edns_field_size(edns)) 824 attach_edns_record(pkt, edns); 825 } 826 827 /** Reply with one string */ 828 static void 829 chaos_replyonestr(sldns_buffer* pkt, const char* str, struct edns_data* edns, 830 struct worker* worker, struct comm_reply* repinfo) 831 { 832 chaos_replystr(pkt, (char**)&str, 1, edns, worker, repinfo); 833 } 834 835 /** 836 * Create CH class trustanchor answer. 837 * @param pkt: buffer 838 * @param edns: edns reply information. 839 * @param w: worker with scratch region. 840 * @param repinfo: reply information for a communication point. 841 */ 842 static void 843 chaos_trustanchor(sldns_buffer* pkt, struct edns_data* edns, struct worker* w, 844 struct comm_reply* repinfo) 845 { 846 #define TA_RESPONSE_MAX_TXT 16 /* max number of TXT records */ 847 #define TA_RESPONSE_MAX_TAGS 32 /* max number of tags printed per zone */ 848 char* str_array[TA_RESPONSE_MAX_TXT]; 849 uint16_t tags[TA_RESPONSE_MAX_TAGS]; 850 int num = 0; 851 struct trust_anchor* ta; 852 853 if(!w->env.need_to_validate) { 854 /* no validator module, reply no trustanchors */ 855 chaos_replystr(pkt, NULL, 0, edns, w, repinfo); 856 return; 857 } 858 859 /* fill the string with contents */ 860 lock_basic_lock(&w->env.anchors->lock); 861 RBTREE_FOR(ta, struct trust_anchor*, w->env.anchors->tree) { 862 char* str; 863 size_t i, numtag, str_len = 255; 864 if(num == TA_RESPONSE_MAX_TXT) continue; 865 str = (char*)regional_alloc(w->scratchpad, str_len); 866 if(!str) continue; 867 lock_basic_lock(&ta->lock); 868 numtag = anchor_list_keytags(ta, tags, TA_RESPONSE_MAX_TAGS); 869 if(numtag == 0) { 870 /* empty, insecure point */ 871 lock_basic_unlock(&ta->lock); 872 continue; 873 } 874 str_array[num] = str; 875 num++; 876 877 /* spool name of anchor */ 878 (void)sldns_wire2str_dname_buf(ta->name, ta->namelen, str, str_len); 879 str_len -= strlen(str); str += strlen(str); 880 /* spool tags */ 881 for(i=0; i<numtag; i++) { 882 snprintf(str, str_len, " %u", (unsigned)tags[i]); 883 str_len -= strlen(str); str += strlen(str); 884 } 885 lock_basic_unlock(&ta->lock); 886 } 887 lock_basic_unlock(&w->env.anchors->lock); 888 889 chaos_replystr(pkt, str_array, num, edns, w, repinfo); 890 regional_free_all(w->scratchpad); 891 } 892 893 /** 894 * Answer CH class queries. 895 * @param w: worker 896 * @param qinfo: query info. Pointer into packet buffer. 897 * @param edns: edns info from query. 898 * @param repinfo: reply information for a communication point. 899 * @param pkt: packet buffer. 900 * @return: true if a reply is to be sent. 901 */ 902 static int 903 answer_chaos(struct worker* w, struct query_info* qinfo, 904 struct edns_data* edns, struct comm_reply* repinfo, sldns_buffer* pkt) 905 { 906 struct config_file* cfg = w->env.cfg; 907 if(qinfo->qtype != LDNS_RR_TYPE_ANY && qinfo->qtype != LDNS_RR_TYPE_TXT) 908 return 0; 909 if(query_dname_compare(qinfo->qname, 910 (uint8_t*)"\002id\006server") == 0 || 911 query_dname_compare(qinfo->qname, 912 (uint8_t*)"\010hostname\004bind") == 0) 913 { 914 if(cfg->hide_identity) 915 return 0; 916 if(cfg->identity==NULL || cfg->identity[0]==0) { 917 char buf[MAXHOSTNAMELEN+1]; 918 if (gethostname(buf, MAXHOSTNAMELEN) == 0) { 919 buf[MAXHOSTNAMELEN] = 0; 920 chaos_replyonestr(pkt, buf, edns, w, repinfo); 921 } else { 922 log_err("gethostname: %s", strerror(errno)); 923 chaos_replyonestr(pkt, "no hostname", edns, w, repinfo); 924 } 925 } 926 else chaos_replyonestr(pkt, cfg->identity, edns, w, repinfo); 927 return 1; 928 } 929 if(query_dname_compare(qinfo->qname, 930 (uint8_t*)"\007version\006server") == 0 || 931 query_dname_compare(qinfo->qname, 932 (uint8_t*)"\007version\004bind") == 0) 933 { 934 if(cfg->hide_version) 935 return 0; 936 if(cfg->version==NULL || cfg->version[0]==0) 937 chaos_replyonestr(pkt, PACKAGE_STRING, edns, w, repinfo); 938 else chaos_replyonestr(pkt, cfg->version, edns, w, repinfo); 939 return 1; 940 } 941 if(query_dname_compare(qinfo->qname, 942 (uint8_t*)"\013trustanchor\007unbound") == 0) 943 { 944 if(cfg->hide_trustanchor) 945 return 0; 946 chaos_trustanchor(pkt, edns, w, repinfo); 947 return 1; 948 } 949 950 return 0; 951 } 952 953 /** 954 * Answer notify queries. These are notifies for authoritative zones, 955 * the reply is an ack that the notify has been received. We need to check 956 * access permission here. 957 * @param w: worker 958 * @param qinfo: query info. Pointer into packet buffer. 959 * @param edns: edns info from query. 960 * @param repinfo: reply info with source address. 961 * @param pkt: packet buffer. 962 */ 963 static void 964 answer_notify(struct worker* w, struct query_info* qinfo, 965 struct edns_data* edns, sldns_buffer* pkt, struct comm_reply* repinfo) 966 { 967 int refused = 0; 968 int rcode = LDNS_RCODE_NOERROR; 969 uint32_t serial = 0; 970 int has_serial; 971 if(!w->env.auth_zones) return; 972 has_serial = auth_zone_parse_notify_serial(pkt, &serial); 973 if(auth_zones_notify(w->env.auth_zones, &w->env, qinfo->qname, 974 qinfo->qname_len, qinfo->qclass, &repinfo->addr, 975 repinfo->addrlen, has_serial, serial, &refused)) { 976 rcode = LDNS_RCODE_NOERROR; 977 } else { 978 if(refused) 979 rcode = LDNS_RCODE_REFUSED; 980 else rcode = LDNS_RCODE_SERVFAIL; 981 } 982 983 if(verbosity >= VERB_DETAIL) { 984 char buf[380]; 985 char zname[255+1]; 986 char sr[25]; 987 dname_str(qinfo->qname, zname); 988 sr[0]=0; 989 if(has_serial) 990 snprintf(sr, sizeof(sr), "serial %u ", 991 (unsigned)serial); 992 if(rcode == LDNS_RCODE_REFUSED) 993 snprintf(buf, sizeof(buf), 994 "refused NOTIFY %sfor %s from", sr, zname); 995 else if(rcode == LDNS_RCODE_SERVFAIL) 996 snprintf(buf, sizeof(buf), 997 "servfail for NOTIFY %sfor %s from", sr, zname); 998 else snprintf(buf, sizeof(buf), 999 "received NOTIFY %sfor %s from", sr, zname); 1000 log_addr(VERB_DETAIL, buf, &repinfo->addr, repinfo->addrlen); 1001 } 1002 edns->edns_version = EDNS_ADVERTISED_VERSION; 1003 edns->udp_size = EDNS_ADVERTISED_SIZE; 1004 edns->ext_rcode = 0; 1005 edns->bits &= EDNS_DO; 1006 error_encode(pkt, rcode, qinfo, 1007 *(uint16_t*)(void *)sldns_buffer_begin(pkt), 1008 sldns_buffer_read_u16_at(pkt, 2), edns); 1009 LDNS_OPCODE_SET(sldns_buffer_begin(pkt), LDNS_PACKET_NOTIFY); 1010 } 1011 1012 static int 1013 deny_refuse(struct comm_point* c, enum acl_access acl, 1014 enum acl_access deny, enum acl_access refuse, 1015 struct worker* worker, struct comm_reply* repinfo) 1016 { 1017 if(acl == deny) { 1018 comm_point_drop_reply(repinfo); 1019 if(worker->stats.extended) 1020 worker->stats.unwanted_queries++; 1021 return 0; 1022 } else if(acl == refuse) { 1023 log_addr(VERB_ALGO, "refused query from", 1024 &repinfo->addr, repinfo->addrlen); 1025 log_buf(VERB_ALGO, "refuse", c->buffer); 1026 if(worker->stats.extended) 1027 worker->stats.unwanted_queries++; 1028 if(worker_check_request(c->buffer, worker) == -1) { 1029 comm_point_drop_reply(repinfo); 1030 return 0; /* discard this */ 1031 } 1032 sldns_buffer_set_limit(c->buffer, LDNS_HEADER_SIZE); 1033 sldns_buffer_write_at(c->buffer, 4, 1034 (uint8_t*)"\0\0\0\0\0\0\0\0", 8); 1035 LDNS_QR_SET(sldns_buffer_begin(c->buffer)); 1036 LDNS_RCODE_SET(sldns_buffer_begin(c->buffer), 1037 LDNS_RCODE_REFUSED); 1038 sldns_buffer_set_position(c->buffer, LDNS_HEADER_SIZE); 1039 sldns_buffer_flip(c->buffer); 1040 return 1; 1041 } 1042 1043 return -1; 1044 } 1045 1046 static int 1047 deny_refuse_all(struct comm_point* c, enum acl_access acl, 1048 struct worker* worker, struct comm_reply* repinfo) 1049 { 1050 return deny_refuse(c, acl, acl_deny, acl_refuse, worker, repinfo); 1051 } 1052 1053 static int 1054 deny_refuse_non_local(struct comm_point* c, enum acl_access acl, 1055 struct worker* worker, struct comm_reply* repinfo) 1056 { 1057 return deny_refuse(c, acl, acl_deny_non_local, acl_refuse_non_local, worker, repinfo); 1058 } 1059 1060 int 1061 worker_handle_request(struct comm_point* c, void* arg, int error, 1062 struct comm_reply* repinfo) 1063 { 1064 struct worker* worker = (struct worker*)arg; 1065 int ret; 1066 hashvalue_type h; 1067 struct lruhash_entry* e; 1068 struct query_info qinfo; 1069 struct edns_data edns; 1070 enum acl_access acl; 1071 struct acl_addr* acladdr; 1072 int rc = 0; 1073 int need_drop = 0; 1074 int is_expired_answer = 0; 1075 int is_secure_answer = 0; 1076 /* We might have to chase a CNAME chain internally, in which case 1077 * we'll have up to two replies and combine them to build a complete 1078 * answer. These variables control this case. */ 1079 struct ub_packed_rrset_key* alias_rrset = NULL; 1080 struct reply_info* partial_rep = NULL; 1081 struct query_info* lookup_qinfo = &qinfo; 1082 struct query_info qinfo_tmp; /* placeholder for lookup_qinfo */ 1083 struct respip_client_info* cinfo = NULL, cinfo_tmp; 1084 memset(&qinfo, 0, sizeof(qinfo)); 1085 1086 if((error != NETEVENT_NOERROR && error != NETEVENT_DONE)|| !repinfo) { 1087 /* some bad tcp query DNS formats give these error calls */ 1088 verbose(VERB_ALGO, "handle request called with err=%d", error); 1089 return 0; 1090 } 1091 #ifdef USE_DNSCRYPT 1092 repinfo->max_udp_size = worker->daemon->cfg->max_udp_size; 1093 if(!dnsc_handle_curved_request(worker->daemon->dnscenv, repinfo)) { 1094 worker->stats.num_query_dnscrypt_crypted_malformed++; 1095 return 0; 1096 } 1097 if(c->dnscrypt && !repinfo->is_dnscrypted) { 1098 char buf[LDNS_MAX_DOMAINLEN+1]; 1099 /* Check if this is unencrypted and asking for certs */ 1100 if(worker_check_request(c->buffer, worker) != 0) { 1101 verbose(VERB_ALGO, 1102 "dnscrypt: worker check request: bad query."); 1103 log_addr(VERB_CLIENT,"from",&repinfo->addr, 1104 repinfo->addrlen); 1105 comm_point_drop_reply(repinfo); 1106 return 0; 1107 } 1108 if(!query_info_parse(&qinfo, c->buffer)) { 1109 verbose(VERB_ALGO, 1110 "dnscrypt: worker parse request: formerror."); 1111 log_addr(VERB_CLIENT, "from", &repinfo->addr, 1112 repinfo->addrlen); 1113 comm_point_drop_reply(repinfo); 1114 return 0; 1115 } 1116 dname_str(qinfo.qname, buf); 1117 if(!(qinfo.qtype == LDNS_RR_TYPE_TXT && 1118 strcasecmp(buf, 1119 worker->daemon->dnscenv->provider_name) == 0)) { 1120 verbose(VERB_ALGO, 1121 "dnscrypt: not TXT \"%s\". Received: %s \"%s\"", 1122 worker->daemon->dnscenv->provider_name, 1123 sldns_rr_descript(qinfo.qtype)->_name, 1124 buf); 1125 comm_point_drop_reply(repinfo); 1126 worker->stats.num_query_dnscrypt_cleartext++; 1127 return 0; 1128 } 1129 worker->stats.num_query_dnscrypt_cert++; 1130 sldns_buffer_rewind(c->buffer); 1131 } else if(c->dnscrypt && repinfo->is_dnscrypted) { 1132 worker->stats.num_query_dnscrypt_crypted++; 1133 } 1134 #endif 1135 #ifdef USE_DNSTAP 1136 /* 1137 * sending src (client)/dst (local service) addresses over DNSTAP from incoming request handler 1138 */ 1139 if(worker->dtenv.log_client_query_messages) { 1140 log_addr(VERB_ALGO, "request from client", &repinfo->addr, repinfo->addrlen); 1141 log_addr(VERB_ALGO, "to local addr", (void*)repinfo->c->socket->addr->ai_addr, repinfo->c->socket->addr->ai_addrlen); 1142 dt_msg_send_client_query(&worker->dtenv, &repinfo->addr, (void*)repinfo->c->socket->addr->ai_addr, c->type, c->buffer); 1143 } 1144 #endif 1145 acladdr = acl_addr_lookup(worker->daemon->acl, &repinfo->addr, 1146 repinfo->addrlen); 1147 acl = acl_get_control(acladdr); 1148 if((ret=deny_refuse_all(c, acl, worker, repinfo)) != -1) 1149 { 1150 if(ret == 1) 1151 goto send_reply; 1152 return ret; 1153 } 1154 if((ret=worker_check_request(c->buffer, worker)) != 0) { 1155 verbose(VERB_ALGO, "worker check request: bad query."); 1156 log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen); 1157 if(ret != -1) { 1158 LDNS_QR_SET(sldns_buffer_begin(c->buffer)); 1159 LDNS_RCODE_SET(sldns_buffer_begin(c->buffer), ret); 1160 return 1; 1161 } 1162 comm_point_drop_reply(repinfo); 1163 return 0; 1164 } 1165 1166 worker->stats.num_queries++; 1167 1168 /* check if this query should be dropped based on source ip rate limiting */ 1169 if(!infra_ip_ratelimit_inc(worker->env.infra_cache, repinfo, 1170 *worker->env.now, 1171 worker->env.cfg->ip_ratelimit_backoff, c->buffer)) { 1172 /* See if we are passed through with slip factor */ 1173 if(worker->env.cfg->ip_ratelimit_factor != 0 && 1174 ub_random_max(worker->env.rnd, 1175 worker->env.cfg->ip_ratelimit_factor) == 0) { 1176 1177 char addrbuf[128]; 1178 addr_to_str(&repinfo->addr, repinfo->addrlen, 1179 addrbuf, sizeof(addrbuf)); 1180 verbose(VERB_QUERY, "ip_ratelimit allowed through for ip address %s because of slip in ip_ratelimit_factor", 1181 addrbuf); 1182 } else { 1183 worker->stats.num_queries_ip_ratelimited++; 1184 comm_point_drop_reply(repinfo); 1185 return 0; 1186 } 1187 } 1188 1189 /* see if query is in the cache */ 1190 if(!query_info_parse(&qinfo, c->buffer)) { 1191 verbose(VERB_ALGO, "worker parse request: formerror."); 1192 log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen); 1193 memset(&qinfo, 0, sizeof(qinfo)); /* zero qinfo.qname */ 1194 if(worker_err_ratelimit(worker, LDNS_RCODE_FORMERR) == -1) { 1195 comm_point_drop_reply(repinfo); 1196 return 0; 1197 } 1198 sldns_buffer_rewind(c->buffer); 1199 LDNS_QR_SET(sldns_buffer_begin(c->buffer)); 1200 LDNS_RCODE_SET(sldns_buffer_begin(c->buffer), 1201 LDNS_RCODE_FORMERR); 1202 goto send_reply; 1203 } 1204 if(worker->env.cfg->log_queries) { 1205 char ip[128]; 1206 addr_to_str(&repinfo->addr, repinfo->addrlen, ip, sizeof(ip)); 1207 log_query_in(ip, qinfo.qname, qinfo.qtype, qinfo.qclass); 1208 } 1209 if(qinfo.qtype == LDNS_RR_TYPE_AXFR || 1210 qinfo.qtype == LDNS_RR_TYPE_IXFR) { 1211 verbose(VERB_ALGO, "worker request: refused zone transfer."); 1212 log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen); 1213 sldns_buffer_rewind(c->buffer); 1214 LDNS_QR_SET(sldns_buffer_begin(c->buffer)); 1215 LDNS_RCODE_SET(sldns_buffer_begin(c->buffer), 1216 LDNS_RCODE_REFUSED); 1217 if(worker->stats.extended) { 1218 worker->stats.qtype[qinfo.qtype]++; 1219 } 1220 goto send_reply; 1221 } 1222 if(qinfo.qtype == LDNS_RR_TYPE_OPT || 1223 qinfo.qtype == LDNS_RR_TYPE_TSIG || 1224 qinfo.qtype == LDNS_RR_TYPE_TKEY || 1225 qinfo.qtype == LDNS_RR_TYPE_MAILA || 1226 qinfo.qtype == LDNS_RR_TYPE_MAILB || 1227 (qinfo.qtype >= 128 && qinfo.qtype <= 248)) { 1228 verbose(VERB_ALGO, "worker request: formerror for meta-type."); 1229 log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen); 1230 if(worker_err_ratelimit(worker, LDNS_RCODE_FORMERR) == -1) { 1231 comm_point_drop_reply(repinfo); 1232 return 0; 1233 } 1234 sldns_buffer_rewind(c->buffer); 1235 LDNS_QR_SET(sldns_buffer_begin(c->buffer)); 1236 LDNS_RCODE_SET(sldns_buffer_begin(c->buffer), 1237 LDNS_RCODE_FORMERR); 1238 if(worker->stats.extended) { 1239 worker->stats.qtype[qinfo.qtype]++; 1240 } 1241 goto send_reply; 1242 } 1243 if((ret=parse_edns_from_query_pkt(c->buffer, &edns, worker->env.cfg, c, 1244 worker->scratchpad)) != 0) { 1245 struct edns_data reply_edns; 1246 verbose(VERB_ALGO, "worker parse edns: formerror."); 1247 log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen); 1248 memset(&reply_edns, 0, sizeof(reply_edns)); 1249 reply_edns.edns_present = 1; 1250 reply_edns.udp_size = EDNS_ADVERTISED_SIZE; 1251 LDNS_RCODE_SET(sldns_buffer_begin(c->buffer), ret); 1252 error_encode(c->buffer, ret, &qinfo, 1253 *(uint16_t*)(void *)sldns_buffer_begin(c->buffer), 1254 sldns_buffer_read_u16_at(c->buffer, 2), &reply_edns); 1255 regional_free_all(worker->scratchpad); 1256 goto send_reply; 1257 } 1258 if(edns.edns_present) { 1259 if(edns.edns_version != 0) { 1260 edns.ext_rcode = (uint8_t)(EDNS_RCODE_BADVERS>>4); 1261 edns.edns_version = EDNS_ADVERTISED_VERSION; 1262 edns.udp_size = EDNS_ADVERTISED_SIZE; 1263 edns.bits &= EDNS_DO; 1264 edns.opt_list_in = NULL; 1265 edns.opt_list_out = NULL; 1266 edns.opt_list_inplace_cb_out = NULL; 1267 edns.padding_block_size = 0; 1268 verbose(VERB_ALGO, "query with bad edns version."); 1269 log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen); 1270 error_encode(c->buffer, EDNS_RCODE_BADVERS&0xf, &qinfo, 1271 *(uint16_t*)(void *)sldns_buffer_begin(c->buffer), 1272 sldns_buffer_read_u16_at(c->buffer, 2), NULL); 1273 if(sldns_buffer_capacity(c->buffer) >= 1274 sldns_buffer_limit(c->buffer)+calc_edns_field_size(&edns)) 1275 attach_edns_record(c->buffer, &edns); 1276 regional_free_all(worker->scratchpad); 1277 goto send_reply; 1278 } 1279 if(edns.udp_size < NORMAL_UDP_SIZE && 1280 worker->daemon->cfg->harden_short_bufsize) { 1281 verbose(VERB_QUERY, "worker request: EDNS bufsize %d ignored", 1282 (int)edns.udp_size); 1283 log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen); 1284 edns.udp_size = NORMAL_UDP_SIZE; 1285 } 1286 } 1287 if(edns.udp_size > worker->daemon->cfg->max_udp_size && 1288 c->type == comm_udp) { 1289 verbose(VERB_QUERY, 1290 "worker request: max UDP reply size modified" 1291 " (%d to max-udp-size)", (int)edns.udp_size); 1292 log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen); 1293 edns.udp_size = worker->daemon->cfg->max_udp_size; 1294 } 1295 if(edns.udp_size < LDNS_HEADER_SIZE) { 1296 verbose(VERB_ALGO, "worker request: edns is too small."); 1297 log_addr(VERB_CLIENT, "from", &repinfo->addr, repinfo->addrlen); 1298 LDNS_QR_SET(sldns_buffer_begin(c->buffer)); 1299 LDNS_TC_SET(sldns_buffer_begin(c->buffer)); 1300 LDNS_RCODE_SET(sldns_buffer_begin(c->buffer), 1301 LDNS_RCODE_SERVFAIL); 1302 sldns_buffer_set_position(c->buffer, LDNS_HEADER_SIZE); 1303 sldns_buffer_write_at(c->buffer, 4, 1304 (uint8_t*)"\0\0\0\0\0\0\0\0", 8); 1305 sldns_buffer_flip(c->buffer); 1306 regional_free_all(worker->scratchpad); 1307 goto send_reply; 1308 } 1309 if(worker->stats.extended) 1310 server_stats_insquery(&worker->stats, c, qinfo.qtype, 1311 qinfo.qclass, &edns, repinfo); 1312 if(c->type != comm_udp) 1313 edns.udp_size = 65535; /* max size for TCP replies */ 1314 if(qinfo.qclass == LDNS_RR_CLASS_CH && answer_chaos(worker, &qinfo, 1315 &edns, repinfo, c->buffer)) { 1316 regional_free_all(worker->scratchpad); 1317 goto send_reply; 1318 } 1319 if(LDNS_OPCODE_WIRE(sldns_buffer_begin(c->buffer)) == 1320 LDNS_PACKET_NOTIFY) { 1321 answer_notify(worker, &qinfo, &edns, c->buffer, repinfo); 1322 regional_free_all(worker->scratchpad); 1323 goto send_reply; 1324 } 1325 if(local_zones_answer(worker->daemon->local_zones, &worker->env, &qinfo, 1326 &edns, c->buffer, worker->scratchpad, repinfo, acladdr->taglist, 1327 acladdr->taglen, acladdr->tag_actions, 1328 acladdr->tag_actions_size, acladdr->tag_datas, 1329 acladdr->tag_datas_size, worker->daemon->cfg->tagname, 1330 worker->daemon->cfg->num_tags, acladdr->view)) { 1331 regional_free_all(worker->scratchpad); 1332 if(sldns_buffer_limit(c->buffer) == 0) { 1333 comm_point_drop_reply(repinfo); 1334 return 0; 1335 } 1336 goto send_reply; 1337 } 1338 if(worker->env.auth_zones && 1339 rpz_callback_from_worker_request(worker->env.auth_zones, 1340 &worker->env, &qinfo, &edns, c->buffer, worker->scratchpad, 1341 repinfo, acladdr->taglist, acladdr->taglen, &worker->stats)) { 1342 regional_free_all(worker->scratchpad); 1343 if(sldns_buffer_limit(c->buffer) == 0) { 1344 comm_point_drop_reply(repinfo); 1345 return 0; 1346 } 1347 goto send_reply; 1348 } 1349 if(worker->env.auth_zones && 1350 auth_zones_answer(worker->env.auth_zones, &worker->env, 1351 &qinfo, &edns, repinfo, c->buffer, worker->scratchpad)) { 1352 regional_free_all(worker->scratchpad); 1353 if(sldns_buffer_limit(c->buffer) == 0) { 1354 comm_point_drop_reply(repinfo); 1355 return 0; 1356 } 1357 /* set RA for everyone that can have recursion (based on 1358 * access control list) */ 1359 if(LDNS_RD_WIRE(sldns_buffer_begin(c->buffer)) && 1360 acl != acl_deny_non_local && acl != acl_refuse_non_local) 1361 LDNS_RA_SET(sldns_buffer_begin(c->buffer)); 1362 goto send_reply; 1363 } 1364 1365 /* We've looked in our local zones. If the answer isn't there, we 1366 * might need to bail out based on ACLs now. */ 1367 if((ret=deny_refuse_non_local(c, acl, worker, repinfo)) != -1) 1368 { 1369 regional_free_all(worker->scratchpad); 1370 if(ret == 1) 1371 goto send_reply; 1372 return ret; 1373 } 1374 1375 /* If this request does not have the recursion bit set, verify 1376 * ACLs allow the recursion bit to be treated as set. */ 1377 if(!(LDNS_RD_WIRE(sldns_buffer_begin(c->buffer))) && 1378 acl == acl_allow_setrd ) { 1379 LDNS_RD_SET(sldns_buffer_begin(c->buffer)); 1380 } 1381 1382 /* If this request does not have the recursion bit set, verify 1383 * ACLs allow the snooping. */ 1384 if(!(LDNS_RD_WIRE(sldns_buffer_begin(c->buffer))) && 1385 acl != acl_allow_snoop ) { 1386 error_encode(c->buffer, LDNS_RCODE_REFUSED, &qinfo, 1387 *(uint16_t*)(void *)sldns_buffer_begin(c->buffer), 1388 sldns_buffer_read_u16_at(c->buffer, 2), NULL); 1389 regional_free_all(worker->scratchpad); 1390 log_addr(VERB_ALGO, "refused nonrec (cache snoop) query from", 1391 &repinfo->addr, repinfo->addrlen); 1392 goto send_reply; 1393 } 1394 1395 /* If we've found a local alias, replace the qname with the alias 1396 * target before resolving it. */ 1397 if(qinfo.local_alias) { 1398 struct ub_packed_rrset_key* rrset = qinfo.local_alias->rrset; 1399 struct packed_rrset_data* d = rrset->entry.data; 1400 1401 /* Sanity check: our current implementation only supports 1402 * a single CNAME RRset as a local alias. */ 1403 if(qinfo.local_alias->next || 1404 rrset->rk.type != htons(LDNS_RR_TYPE_CNAME) || 1405 d->count != 1) { 1406 log_err("assumption failure: unexpected local alias"); 1407 regional_free_all(worker->scratchpad); 1408 return 0; /* drop it */ 1409 } 1410 qinfo.qname = d->rr_data[0] + 2; 1411 qinfo.qname_len = d->rr_len[0] - 2; 1412 } 1413 1414 /* If we may apply IP-based actions to the answer, build the client 1415 * information. As this can be expensive, skip it if there is 1416 * absolutely no possibility of it. */ 1417 if((worker->daemon->use_response_ip || worker->daemon->use_rpz) && 1418 (qinfo.qtype == LDNS_RR_TYPE_A || 1419 qinfo.qtype == LDNS_RR_TYPE_AAAA || 1420 qinfo.qtype == LDNS_RR_TYPE_ANY)) { 1421 cinfo_tmp.taglist = acladdr->taglist; 1422 cinfo_tmp.taglen = acladdr->taglen; 1423 cinfo_tmp.tag_actions = acladdr->tag_actions; 1424 cinfo_tmp.tag_actions_size = acladdr->tag_actions_size; 1425 cinfo_tmp.tag_datas = acladdr->tag_datas; 1426 cinfo_tmp.tag_datas_size = acladdr->tag_datas_size; 1427 cinfo_tmp.view = acladdr->view; 1428 cinfo_tmp.respip_set = worker->daemon->respip_set; 1429 cinfo = &cinfo_tmp; 1430 } 1431 1432 lookup_cache: 1433 /* Lookup the cache. In case we chase an intermediate CNAME chain 1434 * this is a two-pass operation, and lookup_qinfo is different for 1435 * each pass. We should still pass the original qinfo to 1436 * answer_from_cache(), however, since it's used to build the reply. */ 1437 if(!edns_bypass_cache_stage(edns.opt_list_in, &worker->env)) { 1438 is_expired_answer = 0; 1439 is_secure_answer = 0; 1440 h = query_info_hash(lookup_qinfo, sldns_buffer_read_u16_at(c->buffer, 2)); 1441 if((e=slabhash_lookup(worker->env.msg_cache, h, lookup_qinfo, 0))) { 1442 /* answer from cache - we have acquired a readlock on it */ 1443 if(answer_from_cache(worker, &qinfo, 1444 cinfo, &need_drop, &is_expired_answer, &is_secure_answer, 1445 &alias_rrset, &partial_rep, (struct reply_info*)e->data, 1446 *(uint16_t*)(void *)sldns_buffer_begin(c->buffer), 1447 sldns_buffer_read_u16_at(c->buffer, 2), repinfo, 1448 &edns)) { 1449 /* prefetch it if the prefetch TTL expired. 1450 * Note that if there is more than one pass 1451 * its qname must be that used for cache 1452 * lookup. */ 1453 if((worker->env.cfg->prefetch && *worker->env.now >= 1454 ((struct reply_info*)e->data)->prefetch_ttl) || 1455 (worker->env.cfg->serve_expired && 1456 *worker->env.now >= ((struct reply_info*)e->data)->ttl)) { 1457 1458 time_t leeway = ((struct reply_info*)e-> 1459 data)->ttl - *worker->env.now; 1460 if(((struct reply_info*)e->data)->ttl 1461 < *worker->env.now) 1462 leeway = 0; 1463 lock_rw_unlock(&e->lock); 1464 reply_and_prefetch(worker, lookup_qinfo, 1465 sldns_buffer_read_u16_at(c->buffer, 2), 1466 repinfo, leeway, 1467 (partial_rep || need_drop)); 1468 if(!partial_rep) { 1469 rc = 0; 1470 regional_free_all(worker->scratchpad); 1471 goto send_reply_rc; 1472 } 1473 } else if(!partial_rep) { 1474 lock_rw_unlock(&e->lock); 1475 regional_free_all(worker->scratchpad); 1476 goto send_reply; 1477 } else { 1478 /* Note that we've already released the 1479 * lock if we're here after prefetch. */ 1480 lock_rw_unlock(&e->lock); 1481 } 1482 /* We've found a partial reply ending with an 1483 * alias. Replace the lookup qinfo for the 1484 * alias target and lookup the cache again to 1485 * (possibly) complete the reply. As we're 1486 * passing the "base" reply, there will be no 1487 * more alias chasing. */ 1488 memset(&qinfo_tmp, 0, sizeof(qinfo_tmp)); 1489 get_cname_target(alias_rrset, &qinfo_tmp.qname, 1490 &qinfo_tmp.qname_len); 1491 if(!qinfo_tmp.qname) { 1492 log_err("unexpected: invalid answer alias"); 1493 regional_free_all(worker->scratchpad); 1494 return 0; /* drop query */ 1495 } 1496 qinfo_tmp.qtype = qinfo.qtype; 1497 qinfo_tmp.qclass = qinfo.qclass; 1498 lookup_qinfo = &qinfo_tmp; 1499 goto lookup_cache; 1500 } 1501 verbose(VERB_ALGO, "answer from the cache failed"); 1502 lock_rw_unlock(&e->lock); 1503 } 1504 if(!LDNS_RD_WIRE(sldns_buffer_begin(c->buffer))) { 1505 if(answer_norec_from_cache(worker, &qinfo, 1506 *(uint16_t*)(void *)sldns_buffer_begin(c->buffer), 1507 sldns_buffer_read_u16_at(c->buffer, 2), repinfo, 1508 &edns)) { 1509 regional_free_all(worker->scratchpad); 1510 goto send_reply; 1511 } 1512 verbose(VERB_ALGO, "answer norec from cache -- " 1513 "need to validate or not primed"); 1514 } 1515 } 1516 sldns_buffer_rewind(c->buffer); 1517 server_stats_querymiss(&worker->stats, worker); 1518 1519 if(verbosity >= VERB_CLIENT) { 1520 if(c->type == comm_udp) 1521 log_addr(VERB_CLIENT, "udp request from", 1522 &repinfo->addr, repinfo->addrlen); 1523 else log_addr(VERB_CLIENT, "tcp request from", 1524 &repinfo->addr, repinfo->addrlen); 1525 } 1526 1527 /* grab a work request structure for this new request */ 1528 mesh_new_client(worker->env.mesh, &qinfo, cinfo, 1529 sldns_buffer_read_u16_at(c->buffer, 2), 1530 &edns, repinfo, *(uint16_t*)(void *)sldns_buffer_begin(c->buffer)); 1531 regional_free_all(worker->scratchpad); 1532 worker_mem_report(worker, NULL); 1533 return 0; 1534 1535 send_reply: 1536 rc = 1; 1537 send_reply_rc: 1538 if(need_drop) { 1539 comm_point_drop_reply(repinfo); 1540 return 0; 1541 } 1542 if(is_expired_answer) { 1543 worker->stats.ans_expired++; 1544 } 1545 server_stats_insrcode(&worker->stats, c->buffer); 1546 if(worker->stats.extended) { 1547 if(is_secure_answer) worker->stats.ans_secure++; 1548 } 1549 #ifdef USE_DNSTAP 1550 /* 1551 * sending src (client)/dst (local service) addresses over DNSTAP from send_reply code label (when we serviced local zone for ex.) 1552 */ 1553 if(worker->dtenv.log_client_response_messages) { 1554 log_addr(VERB_ALGO, "from local addr", (void*)repinfo->c->socket->addr->ai_addr, repinfo->c->socket->addr->ai_addrlen); 1555 log_addr(VERB_ALGO, "response to client", &repinfo->addr, repinfo->addrlen); 1556 dt_msg_send_client_response(&worker->dtenv, &repinfo->addr, (void*)repinfo->c->socket->addr->ai_addr, c->type, c->buffer); 1557 } 1558 #endif 1559 if(worker->env.cfg->log_replies) 1560 { 1561 struct timeval tv; 1562 memset(&tv, 0, sizeof(tv)); 1563 if(qinfo.local_alias && qinfo.local_alias->rrset && 1564 qinfo.local_alias->rrset->rk.dname) { 1565 /* log original qname, before the local alias was 1566 * used to resolve that CNAME to something else */ 1567 qinfo.qname = qinfo.local_alias->rrset->rk.dname; 1568 log_reply_info(NO_VERBOSE, &qinfo, &repinfo->addr, repinfo->addrlen, 1569 tv, 1, c->buffer); 1570 } else { 1571 log_reply_info(NO_VERBOSE, &qinfo, &repinfo->addr, repinfo->addrlen, 1572 tv, 1, c->buffer); 1573 } 1574 } 1575 #ifdef USE_DNSCRYPT 1576 if(!dnsc_handle_uncurved_request(repinfo)) { 1577 return 0; 1578 } 1579 #endif 1580 return rc; 1581 } 1582 1583 void 1584 worker_sighandler(int sig, void* arg) 1585 { 1586 /* note that log, print, syscalls here give race conditions. 1587 * And cause hangups if the log-lock is held by the application. */ 1588 struct worker* worker = (struct worker*)arg; 1589 switch(sig) { 1590 #ifdef SIGHUP 1591 case SIGHUP: 1592 comm_base_exit(worker->base); 1593 break; 1594 #endif 1595 case SIGINT: 1596 worker->need_to_exit = 1; 1597 comm_base_exit(worker->base); 1598 break; 1599 #ifdef SIGQUIT 1600 case SIGQUIT: 1601 worker->need_to_exit = 1; 1602 comm_base_exit(worker->base); 1603 break; 1604 #endif 1605 case SIGTERM: 1606 worker->need_to_exit = 1; 1607 comm_base_exit(worker->base); 1608 break; 1609 default: 1610 /* unknown signal, ignored */ 1611 break; 1612 } 1613 } 1614 1615 /** restart statistics timer for worker, if enabled */ 1616 static void 1617 worker_restart_timer(struct worker* worker) 1618 { 1619 if(worker->env.cfg->stat_interval > 0) { 1620 struct timeval tv; 1621 #ifndef S_SPLINT_S 1622 tv.tv_sec = worker->env.cfg->stat_interval; 1623 tv.tv_usec = 0; 1624 #endif 1625 comm_timer_set(worker->stat_timer, &tv); 1626 } 1627 } 1628 1629 void worker_stat_timer_cb(void* arg) 1630 { 1631 struct worker* worker = (struct worker*)arg; 1632 server_stats_log(&worker->stats, worker, worker->thread_num); 1633 mesh_stats(worker->env.mesh, "mesh has"); 1634 worker_mem_report(worker, NULL); 1635 /* SHM is enabled, process data to SHM */ 1636 if (worker->daemon->cfg->shm_enable) { 1637 shm_main_run(worker); 1638 } 1639 if(!worker->daemon->cfg->stat_cumulative) { 1640 worker_stats_clear(worker); 1641 } 1642 /* start next timer */ 1643 worker_restart_timer(worker); 1644 } 1645 1646 void worker_probe_timer_cb(void* arg) 1647 { 1648 struct worker* worker = (struct worker*)arg; 1649 struct timeval tv; 1650 #ifndef S_SPLINT_S 1651 tv.tv_sec = (time_t)autr_probe_timer(&worker->env); 1652 tv.tv_usec = 0; 1653 #endif 1654 if(tv.tv_sec != 0) 1655 comm_timer_set(worker->env.probe_timer, &tv); 1656 } 1657 1658 struct worker* 1659 worker_create(struct daemon* daemon, int id, int* ports, int n) 1660 { 1661 unsigned int seed; 1662 struct worker* worker = (struct worker*)calloc(1, 1663 sizeof(struct worker)); 1664 if(!worker) 1665 return NULL; 1666 worker->numports = n; 1667 worker->ports = (int*)memdup(ports, sizeof(int)*n); 1668 if(!worker->ports) { 1669 free(worker); 1670 return NULL; 1671 } 1672 worker->daemon = daemon; 1673 worker->thread_num = id; 1674 if(!(worker->cmd = tube_create())) { 1675 free(worker->ports); 1676 free(worker); 1677 return NULL; 1678 } 1679 /* create random state here to avoid locking trouble in RAND_bytes */ 1680 if(!(worker->rndstate = ub_initstate(daemon->rand))) { 1681 log_err("could not init random numbers."); 1682 tube_delete(worker->cmd); 1683 free(worker->ports); 1684 free(worker); 1685 return NULL; 1686 } 1687 explicit_bzero(&seed, sizeof(seed)); 1688 return worker; 1689 } 1690 1691 int 1692 worker_init(struct worker* worker, struct config_file *cfg, 1693 struct listen_port* ports, int do_sigs) 1694 { 1695 #ifdef USE_DNSTAP 1696 struct dt_env* dtenv = &worker->dtenv; 1697 #else 1698 void* dtenv = NULL; 1699 #endif 1700 worker->need_to_exit = 0; 1701 worker->base = comm_base_create(do_sigs); 1702 if(!worker->base) { 1703 log_err("could not create event handling base"); 1704 worker_delete(worker); 1705 return 0; 1706 } 1707 comm_base_set_slow_accept_handlers(worker->base, &worker_stop_accept, 1708 &worker_start_accept, worker); 1709 if(do_sigs) { 1710 #ifdef SIGHUP 1711 ub_thread_sig_unblock(SIGHUP); 1712 #endif 1713 ub_thread_sig_unblock(SIGINT); 1714 #ifdef SIGQUIT 1715 ub_thread_sig_unblock(SIGQUIT); 1716 #endif 1717 ub_thread_sig_unblock(SIGTERM); 1718 #ifndef LIBEVENT_SIGNAL_PROBLEM 1719 worker->comsig = comm_signal_create(worker->base, 1720 worker_sighandler, worker); 1721 if(!worker->comsig 1722 #ifdef SIGHUP 1723 || !comm_signal_bind(worker->comsig, SIGHUP) 1724 #endif 1725 #ifdef SIGQUIT 1726 || !comm_signal_bind(worker->comsig, SIGQUIT) 1727 #endif 1728 || !comm_signal_bind(worker->comsig, SIGTERM) 1729 || !comm_signal_bind(worker->comsig, SIGINT)) { 1730 log_err("could not create signal handlers"); 1731 worker_delete(worker); 1732 return 0; 1733 } 1734 #endif /* LIBEVENT_SIGNAL_PROBLEM */ 1735 if(!daemon_remote_open_accept(worker->daemon->rc, 1736 worker->daemon->rc_ports, worker)) { 1737 worker_delete(worker); 1738 return 0; 1739 } 1740 #ifdef UB_ON_WINDOWS 1741 wsvc_setup_worker(worker); 1742 #endif /* UB_ON_WINDOWS */ 1743 } else { /* !do_sigs */ 1744 worker->comsig = NULL; 1745 } 1746 #ifdef USE_DNSTAP 1747 if(cfg->dnstap) { 1748 log_assert(worker->daemon->dtenv != NULL); 1749 memcpy(&worker->dtenv, worker->daemon->dtenv, sizeof(struct dt_env)); 1750 if(!dt_init(&worker->dtenv, worker->base)) 1751 fatal_exit("dt_init failed"); 1752 } 1753 #endif 1754 worker->front = listen_create(worker->base, ports, 1755 cfg->msg_buffer_size, (int)cfg->incoming_num_tcp, 1756 cfg->do_tcp_keepalive 1757 ? cfg->tcp_keepalive_timeout 1758 : cfg->tcp_idle_timeout, 1759 cfg->harden_large_queries, cfg->http_max_streams, 1760 cfg->http_endpoint, cfg->http_notls_downstream, 1761 worker->daemon->tcl, worker->daemon->listen_sslctx, 1762 dtenv, worker_handle_request, worker); 1763 if(!worker->front) { 1764 log_err("could not create listening sockets"); 1765 worker_delete(worker); 1766 return 0; 1767 } 1768 worker->back = outside_network_create(worker->base, 1769 cfg->msg_buffer_size, (size_t)cfg->outgoing_num_ports, 1770 cfg->out_ifs, cfg->num_out_ifs, cfg->do_ip4, cfg->do_ip6, 1771 cfg->do_tcp?cfg->outgoing_num_tcp:0, cfg->ip_dscp, 1772 worker->daemon->env->infra_cache, worker->rndstate, 1773 cfg->use_caps_bits_for_id, worker->ports, worker->numports, 1774 cfg->unwanted_threshold, cfg->outgoing_tcp_mss, 1775 &worker_alloc_cleanup, worker, 1776 cfg->do_udp || cfg->udp_upstream_without_downstream, 1777 worker->daemon->connect_sslctx, cfg->delay_close, 1778 cfg->tls_use_sni, dtenv, cfg->udp_connect, 1779 cfg->max_reuse_tcp_queries, cfg->tcp_reuse_timeout, 1780 cfg->tcp_auth_query_timeout); 1781 if(!worker->back) { 1782 log_err("could not create outgoing sockets"); 1783 worker_delete(worker); 1784 return 0; 1785 } 1786 iterator_set_ip46_support(&worker->daemon->mods, worker->daemon->env, 1787 worker->back); 1788 /* start listening to commands */ 1789 if(!tube_setup_bg_listen(worker->cmd, worker->base, 1790 &worker_handle_control_cmd, worker)) { 1791 log_err("could not create control compt."); 1792 worker_delete(worker); 1793 return 0; 1794 } 1795 worker->stat_timer = comm_timer_create(worker->base, 1796 worker_stat_timer_cb, worker); 1797 if(!worker->stat_timer) { 1798 log_err("could not create statistics timer"); 1799 } 1800 1801 /* we use the msg_buffer_size as a good estimate for what the 1802 * user wants for memory usage sizes */ 1803 worker->scratchpad = regional_create_custom(cfg->msg_buffer_size); 1804 if(!worker->scratchpad) { 1805 log_err("malloc failure"); 1806 worker_delete(worker); 1807 return 0; 1808 } 1809 1810 server_stats_init(&worker->stats, cfg); 1811 alloc_init(&worker->alloc, &worker->daemon->superalloc, 1812 worker->thread_num); 1813 alloc_set_id_cleanup(&worker->alloc, &worker_alloc_cleanup, worker); 1814 worker->env = *worker->daemon->env; 1815 comm_base_timept(worker->base, &worker->env.now, &worker->env.now_tv); 1816 worker->env.worker = worker; 1817 worker->env.worker_base = worker->base; 1818 worker->env.send_query = &worker_send_query; 1819 worker->env.alloc = &worker->alloc; 1820 worker->env.outnet = worker->back; 1821 worker->env.rnd = worker->rndstate; 1822 /* If case prefetch is triggered, the corresponding mesh will clear 1823 * the scratchpad for the module env in the middle of request handling. 1824 * It would be prone to a use-after-free kind of bug, so we avoid 1825 * sharing it with worker's own scratchpad at the cost of having 1826 * one more pad per worker. */ 1827 worker->env.scratch = regional_create_custom(cfg->msg_buffer_size); 1828 if(!worker->env.scratch) { 1829 log_err("malloc failure"); 1830 worker_delete(worker); 1831 return 0; 1832 } 1833 worker->env.mesh = mesh_create(&worker->daemon->mods, &worker->env); 1834 if(!worker->env.mesh) { 1835 log_err("malloc failure"); 1836 worker_delete(worker); 1837 return 0; 1838 } 1839 /* Pass on daemon variables that we would need in the mesh area */ 1840 worker->env.mesh->use_response_ip = worker->daemon->use_response_ip; 1841 worker->env.mesh->use_rpz = worker->daemon->use_rpz; 1842 1843 worker->env.detach_subs = &mesh_detach_subs; 1844 worker->env.attach_sub = &mesh_attach_sub; 1845 worker->env.add_sub = &mesh_add_sub; 1846 worker->env.kill_sub = &mesh_state_delete; 1847 worker->env.detect_cycle = &mesh_detect_cycle; 1848 worker->env.scratch_buffer = sldns_buffer_new(cfg->msg_buffer_size); 1849 if(!worker->env.scratch_buffer) { 1850 log_err("malloc failure"); 1851 worker_delete(worker); 1852 return 0; 1853 } 1854 if(!(worker->env.fwds = forwards_create()) || 1855 !forwards_apply_cfg(worker->env.fwds, cfg)) { 1856 log_err("Could not set forward zones"); 1857 worker_delete(worker); 1858 return 0; 1859 } 1860 if(!(worker->env.hints = hints_create()) || 1861 !hints_apply_cfg(worker->env.hints, cfg)) { 1862 log_err("Could not set root or stub hints"); 1863 worker_delete(worker); 1864 return 0; 1865 } 1866 /* one probe timer per process -- if we have 5011 anchors */ 1867 if(autr_get_num_anchors(worker->env.anchors) > 0 1868 #ifndef THREADS_DISABLED 1869 && worker->thread_num == 0 1870 #endif 1871 ) { 1872 struct timeval tv; 1873 tv.tv_sec = 0; 1874 tv.tv_usec = 0; 1875 worker->env.probe_timer = comm_timer_create(worker->base, 1876 worker_probe_timer_cb, worker); 1877 if(!worker->env.probe_timer) { 1878 log_err("could not create 5011-probe timer"); 1879 } else { 1880 /* let timer fire, then it can reset itself */ 1881 comm_timer_set(worker->env.probe_timer, &tv); 1882 } 1883 } 1884 /* zone transfer tasks, setup once per process, if any */ 1885 if(worker->env.auth_zones 1886 #ifndef THREADS_DISABLED 1887 && worker->thread_num == 0 1888 #endif 1889 ) { 1890 auth_xfer_pickup_initial(worker->env.auth_zones, &worker->env); 1891 auth_zones_pickup_zonemd_verify(worker->env.auth_zones, 1892 &worker->env); 1893 } 1894 #ifdef USE_DNSTAP 1895 if(worker->daemon->cfg->dnstap 1896 #ifndef THREADS_DISABLED 1897 && worker->thread_num == 0 1898 #endif 1899 ) { 1900 if(!dt_io_thread_start(dtenv->dtio, comm_base_internal( 1901 worker->base), worker->daemon->num)) { 1902 log_err("could not start dnstap io thread"); 1903 worker_delete(worker); 1904 return 0; 1905 } 1906 } 1907 #endif /* USE_DNSTAP */ 1908 worker_mem_report(worker, NULL); 1909 /* if statistics enabled start timer */ 1910 if(worker->env.cfg->stat_interval > 0) { 1911 verbose(VERB_ALGO, "set statistics interval %d secs", 1912 worker->env.cfg->stat_interval); 1913 worker_restart_timer(worker); 1914 } 1915 return 1; 1916 } 1917 1918 void 1919 worker_work(struct worker* worker) 1920 { 1921 comm_base_dispatch(worker->base); 1922 } 1923 1924 void 1925 worker_delete(struct worker* worker) 1926 { 1927 if(!worker) 1928 return; 1929 if(worker->env.mesh && verbosity >= VERB_OPS) { 1930 server_stats_log(&worker->stats, worker, worker->thread_num); 1931 mesh_stats(worker->env.mesh, "mesh has"); 1932 worker_mem_report(worker, NULL); 1933 } 1934 outside_network_quit_prepare(worker->back); 1935 mesh_delete(worker->env.mesh); 1936 sldns_buffer_free(worker->env.scratch_buffer); 1937 forwards_delete(worker->env.fwds); 1938 hints_delete(worker->env.hints); 1939 listen_delete(worker->front); 1940 outside_network_delete(worker->back); 1941 comm_signal_delete(worker->comsig); 1942 tube_delete(worker->cmd); 1943 comm_timer_delete(worker->stat_timer); 1944 comm_timer_delete(worker->env.probe_timer); 1945 free(worker->ports); 1946 if(worker->thread_num == 0) { 1947 #ifdef UB_ON_WINDOWS 1948 wsvc_desetup_worker(worker); 1949 #endif /* UB_ON_WINDOWS */ 1950 } 1951 #ifdef USE_DNSTAP 1952 if(worker->daemon->cfg->dnstap 1953 #ifndef THREADS_DISABLED 1954 && worker->thread_num == 0 1955 #endif 1956 ) { 1957 dt_io_thread_stop(worker->dtenv.dtio); 1958 } 1959 dt_deinit(&worker->dtenv); 1960 #endif /* USE_DNSTAP */ 1961 comm_base_delete(worker->base); 1962 ub_randfree(worker->rndstate); 1963 alloc_clear(&worker->alloc); 1964 regional_destroy(worker->env.scratch); 1965 regional_destroy(worker->scratchpad); 1966 free(worker); 1967 } 1968 1969 struct outbound_entry* 1970 worker_send_query(struct query_info* qinfo, uint16_t flags, int dnssec, 1971 int want_dnssec, int nocaps, int check_ratelimit, 1972 struct sockaddr_storage* addr, socklen_t addrlen, uint8_t* zone, 1973 size_t zonelen, int tcp_upstream, int ssl_upstream, char* tls_auth_name, 1974 struct module_qstate* q, int* was_ratelimited) 1975 { 1976 struct worker* worker = q->env->worker; 1977 struct outbound_entry* e = (struct outbound_entry*)regional_alloc( 1978 q->region, sizeof(*e)); 1979 if(!e) 1980 return NULL; 1981 e->qstate = q; 1982 e->qsent = outnet_serviced_query(worker->back, qinfo, flags, dnssec, 1983 want_dnssec, nocaps, check_ratelimit, tcp_upstream, 1984 ssl_upstream, tls_auth_name, addr, addrlen, zone, zonelen, q, 1985 worker_handle_service_reply, e, worker->back->udp_buff, q->env, 1986 was_ratelimited); 1987 if(!e->qsent) { 1988 return NULL; 1989 } 1990 return e; 1991 } 1992 1993 void 1994 worker_alloc_cleanup(void* arg) 1995 { 1996 struct worker* worker = (struct worker*)arg; 1997 slabhash_clear(&worker->env.rrset_cache->table); 1998 slabhash_clear(worker->env.msg_cache); 1999 } 2000 2001 void worker_stats_clear(struct worker* worker) 2002 { 2003 server_stats_init(&worker->stats, worker->env.cfg); 2004 mesh_stats_clear(worker->env.mesh); 2005 worker->back->unwanted_replies = 0; 2006 worker->back->num_tcp_outgoing = 0; 2007 } 2008 2009 void worker_start_accept(void* arg) 2010 { 2011 struct worker* worker = (struct worker*)arg; 2012 listen_start_accept(worker->front); 2013 if(worker->thread_num == 0) 2014 daemon_remote_start_accept(worker->daemon->rc); 2015 } 2016 2017 void worker_stop_accept(void* arg) 2018 { 2019 struct worker* worker = (struct worker*)arg; 2020 listen_stop_accept(worker->front); 2021 if(worker->thread_num == 0) 2022 daemon_remote_stop_accept(worker->daemon->rc); 2023 } 2024 2025 /* --- fake callbacks for fptr_wlist to work --- */ 2026 struct outbound_entry* libworker_send_query( 2027 struct query_info* ATTR_UNUSED(qinfo), 2028 uint16_t ATTR_UNUSED(flags), int ATTR_UNUSED(dnssec), 2029 int ATTR_UNUSED(want_dnssec), int ATTR_UNUSED(nocaps), 2030 int ATTR_UNUSED(check_ratelimit), 2031 struct sockaddr_storage* ATTR_UNUSED(addr), socklen_t ATTR_UNUSED(addrlen), 2032 uint8_t* ATTR_UNUSED(zone), size_t ATTR_UNUSED(zonelen), int ATTR_UNUSED(tcp_upstream), 2033 int ATTR_UNUSED(ssl_upstream), char* ATTR_UNUSED(tls_auth_name), 2034 struct module_qstate* ATTR_UNUSED(q), int* ATTR_UNUSED(was_ratelimited)) 2035 { 2036 log_assert(0); 2037 return 0; 2038 } 2039 2040 int libworker_handle_service_reply(struct comm_point* ATTR_UNUSED(c), 2041 void* ATTR_UNUSED(arg), int ATTR_UNUSED(error), 2042 struct comm_reply* ATTR_UNUSED(reply_info)) 2043 { 2044 log_assert(0); 2045 return 0; 2046 } 2047 2048 void libworker_handle_control_cmd(struct tube* ATTR_UNUSED(tube), 2049 uint8_t* ATTR_UNUSED(buffer), size_t ATTR_UNUSED(len), 2050 int ATTR_UNUSED(error), void* ATTR_UNUSED(arg)) 2051 { 2052 log_assert(0); 2053 } 2054 2055 void libworker_fg_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode), 2056 sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s), 2057 char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited)) 2058 { 2059 log_assert(0); 2060 } 2061 2062 void libworker_bg_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode), 2063 sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s), 2064 char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited)) 2065 { 2066 log_assert(0); 2067 } 2068 2069 void libworker_event_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode), 2070 sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s), 2071 char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited)) 2072 { 2073 log_assert(0); 2074 } 2075 2076 int context_query_cmp(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b)) 2077 { 2078 log_assert(0); 2079 return 0; 2080 } 2081 2082 int order_lock_cmp(const void* ATTR_UNUSED(e1), const void* ATTR_UNUSED(e2)) 2083 { 2084 log_assert(0); 2085 return 0; 2086 } 2087 2088 int codeline_cmp(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b)) 2089 { 2090 log_assert(0); 2091 return 0; 2092 } 2093 2094 #ifdef USE_DNSTAP 2095 void dtio_tap_callback(int ATTR_UNUSED(fd), short ATTR_UNUSED(ev), 2096 void* ATTR_UNUSED(arg)) 2097 { 2098 log_assert(0); 2099 } 2100 #endif 2101 2102 #ifdef USE_DNSTAP 2103 void dtio_mainfdcallback(int ATTR_UNUSED(fd), short ATTR_UNUSED(ev), 2104 void* ATTR_UNUSED(arg)) 2105 { 2106 log_assert(0); 2107 } 2108 #endif 2109