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