Debian Codegraph @

src/forward.c

raw
1 /* dnsmasq is Copyright (c) 2000-2026 Simon Kelley
2
3 This program is free software; you can redistribute it and/or modify
4 it under the terms of the GNU General Public License as published by
5 the Free Software Foundation; version 2 dated June, 1991, or
6 (at your option) version 3 dated 29 June, 2007.
7
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
12
13 You should have received a copy of the GNU General Public License
14 along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16
17 #include "dnsmasq.h"
18
19 static struct frec *get_new_frec(time_t now, struct server *serv, int force);
20 static struct frec *lookup_frec(time_t now, char *target, int class, int rrtype, int id, int flags, int flagmask);
21 #ifdef HAVE_DNSSEC
22 static int tcp_key_recurse(time_t now, int status, struct dns_header *header, size_t n,
23 int class, char *name, char *keyname, struct server *server,
24 int have_mark, unsigned int mark, int *keycount, int *validatecount);
25 #endif
26 static unsigned short get_id(void);
27 static void free_frec(struct frec *f);
28 static void query_full(time_t now, char *domain);
29
30 /* Send a UDP packet with its source address set as "source"
31 unless nowild is true, when we just send it with the kernel default */
32 int send_from(int fd, int nowild, char *packet, size_t len,
33 union mysockaddr *to, union all_addr *source,
34 unsigned int iface)
35 {
36 struct msghdr msg;
37 struct iovec iov[1];
38 union {
39 struct cmsghdr align; /* this ensures alignment */
40 #if defined(HAVE_LINUX_NETWORK)
41 char control[CMSG_SPACE(sizeof(struct in_pktinfo))];
42 #elif defined(IP_SENDSRCADDR)
43 char control[CMSG_SPACE(sizeof(struct in_addr))];
44 #endif
45 char control6[CMSG_SPACE(sizeof(struct in6_pktinfo))];
46 } control_u;
47
48 iov[0].iov_base = packet;
49 iov[0].iov_len = len;
50
51 msg.msg_control = NULL;
52 msg.msg_controllen = 0;
53 msg.msg_flags = 0;
54 msg.msg_name = to;
55 msg.msg_namelen = sa_len(to);
56 msg.msg_iov = iov;
57 msg.msg_iovlen = 1;
58
59 if (!nowild)
60 {
61 struct cmsghdr *cmptr = msg.msg_control = &control_u.align;
62
63 /* alignment padding passed to the kernel should not be uninitialised. */
64 memset(&control_u, 0, sizeof(control_u));
65
66 if (to->sa.sa_family == AF_INET)
67 {
68 #if defined(HAVE_LINUX_NETWORK)
69 struct in_pktinfo *p = (struct in_pktinfo *)CMSG_DATA(cmptr);;
70 p->ipi_ifindex = 0;
71 p->ipi_spec_dst = source->addr4;
72 msg.msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo));
73 cmptr->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
74 cmptr->cmsg_level = IPPROTO_IP;
75 cmptr->cmsg_type = IP_PKTINFO;
76 #elif defined(IP_SENDSRCADDR)
77 msg.msg_controllen = CMSG_SPACE(sizeof(struct in_addr));
78 memcpy(CMSG_DATA(cmptr), &(source->addr4), sizeof(source->addr4));
79 cmptr->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
80 cmptr->cmsg_level = IPPROTO_IP;
81 cmptr->cmsg_type = IP_SENDSRCADDR;
82 #endif
83 }
84 else
85 {
86 struct in6_pktinfo *p = (struct in6_pktinfo *)CMSG_DATA(cmptr);
87 p->ipi6_ifindex = iface; /* Need iface for IPv6 to handle link-local addrs */
88 p->ipi6_addr = source->addr6;
89 msg.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
90 cmptr->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
91 cmptr->cmsg_type = daemon->v6pktinfo;
92 cmptr->cmsg_level = IPPROTO_IPV6;
93 }
94 }
95
96 while (retry_send(sendmsg(fd, &msg, 0)));
97
98 if (errno != 0)
99 {
100 #ifdef HAVE_LINUX_NETWORK
101 /* If interface is still in DAD, EINVAL results - ignore that. */
102 if (errno != EINVAL)
103 my_syslog(LOG_ERR, _("failed to send packet: %s"), strerror(errno));
104 #endif
105 return 0;
106 }
107
108 return 1;
109 }
110
111 #ifdef HAVE_CONNTRACK
112 static void set_outgoing_mark(struct frec *forward, int fd)
113 {
114 /* Copy connection mark of incoming query to outgoing connection. */
115 unsigned int mark;
116 if (get_incoming_mark(&forward->frec_src.source, &forward->frec_src.dest, 0, &mark))
117 setsockopt(fd, SOL_SOCKET, SO_MARK, &mark, sizeof(unsigned int));
118 }
119 #endif
120
121 static void log_query_mysockaddr(unsigned int flags, char *name, union mysockaddr *addr, char *arg, unsigned short type)
122 {
123 if (addr->sa.sa_family == AF_INET)
124 {
125 if (flags & F_SERVER)
126 type = ntohs(addr->in.sin_port);
127 log_query(flags | F_IPV4, name, (union all_addr *)&addr->in.sin_addr, arg, type);
128 }
129 else
130 {
131 if (flags & F_SERVER)
132 type = ntohs(addr->in6.sin6_port);
133 log_query(flags | F_IPV6, name, (union all_addr *)&addr->in6.sin6_addr, arg, type);
134 }
135 }
136
137 static void server_send(struct server *server, int fd,
138 const void *header, size_t plen)
139 {
140 while (retry_send(sendto(fd, header, plen, 0,
141 &server->addr.sa,
142 sa_len(&server->addr))));
143 }
144
145 static int domain_no_rebind(char *domain)
146 {
147 struct rebind_domain *rbd;
148 size_t tlen, dlen = strlen(domain);
149 char *dots = strchr(domain, '.');
150
151 /* Match whole labels only. Empty domain matches no dots (any single label) */
152 for (rbd = daemon->no_rebind; rbd; rbd = rbd->next)
153 {
154 if (dlen >= (tlen = strlen(rbd->domain)) &&
155 hostname_isequal(rbd->domain, &domain[dlen - tlen]) &&
156 (dlen == tlen || domain[dlen - tlen - 1] == '.'))
157 return 1;
158
159 if (tlen == 0 && !dots)
160 return 1;
161 }
162
163 return 0;
164 }
165
166 static void forward_query(int udpfd, union mysockaddr *udpaddr,
167 union all_addr *dst_addr, unsigned int dst_iface,
168 struct dns_header *header, size_t plen, size_t replylimit, time_t now,
169 struct frec *forward, unsigned int fwd_flags, int fast_retry)
170 {
171 unsigned int flags = 0;
172 int is_dnssec = forward && (forward->flags & (FREC_DNSKEY_QUERY | FREC_DS_QUERY));
173 struct server *master;
174 unsigned int gotname;
175 int old_src = 0, old_reply = 0;
176 int first, last, start = 0;
177 int forwarded = 0;
178 int ede = EDE_UNSET;
179 unsigned short rrtype, rrclass;
180
181 gotname = extract_request(header, plen, daemon->namebuff, &rrtype, &rrclass);
182
183 /* Check for retry on existing query.
184 FREC_DNSKEY and FREC_DS_QUERY are never set in flags, so the test below
185 ensures that no frec created for internal DNSSEC query can be returned here.
186
187 Similarly FREC_NO_CACHE is never set in flags, so a query which is
188 contigent on a particular source address EDNS0 option will never be matched. */
189 if (forward)
190 {
191 old_src = 1;
192 old_reply = 1;
193 fwd_flags = forward->flags;
194 }
195 else if (gotname && (forward = lookup_frec(now, daemon->namebuff, (int)rrclass, (int)rrtype, -1, fwd_flags,
196 FREC_CHECKING_DISABLED | FREC_AD_QUESTION | FREC_DO_QUESTION |
197 FREC_HAS_PHEADER | FREC_DNSKEY_QUERY | FREC_DS_QUERY | FREC_NO_CACHE)))
198 {
199 struct frec_src *src;
200 unsigned int casediff = 0;
201 unsigned int *bitvector = NULL;
202 unsigned short id = ntohs(header->id); /* Retrieve the id from the new query before we overwrite it. */
203
204 /* Get the case-scambled version of the query to resend. This is important because we
205 may fall through below and forward the query in the packet buffer again and we
206 want to use the same case scrambling as the first time. */
207 blockdata_retrieve(forward->stash, forward->stash_len, (void *)header);
208 plen = forward->stash_len;
209
210 for (src = &forward->frec_src; src; src = src->next)
211 if (src->orig_id == id &&
212 sockaddr_isequal(&src->source, udpaddr))
213 break;
214
215 if (src)
216 {
217 old_src = 1;
218 /* If a query is retried, use the log_id for the retry when logging the answer. */
219 src->log_id = daemon->log_id;
220 }
221 else
222 {
223 /* Existing query, but from new source, just add this
224 client to the list that will get the reply.*/
225
226 /* Note whine_malloc() zeros memory. */
227 if (!daemon->free_frec_src &&
228 daemon->frec_src_count < daemon->ftabsize &&
229 (daemon->free_frec_src = whine_malloc(sizeof(struct frec_src))))
230 {
231 daemon->frec_src_count++;
232 daemon->free_frec_src->next = NULL;
233 daemon->free_frec_src->encode_bigmap = NULL;
234 }
235
236 /* If we've been spammed with many duplicates, return REFUSED. */
237 if (!daemon->free_frec_src)
238 {
239 query_full(now, NULL);
240 /* This is tricky; if we're blasted with the same query
241 over and over, we'll end up taking this path each time
242 and never resetting until the frec gets deleted by
243 aging followed by the receipt of a different query. This
244 is a bit of a DoS vuln. Avoid by explicitly deleting the
245 frec once it expires. */
246 if (difftime(now, forward->time) >= TIMEOUT)
247 free_frec(forward);
248 goto reply;
249 }
250
251 /* Find a bitmap of case differences between the query sent upstream and this one,
252 so we can reply to each query with the correct case pattern.
253 Since we need this to get back the exact case pattern of each query when doing
254 query combining, we have to handle the (rare) case that there are case differences
255 beyond the first 32 letters.
256 If that happens we have to allocate memory to save it, and the casediff variable
257 holds the length of that array.
258 Mismatches beyond 32 letters are rare because most queries are all lowercase and
259 we only scramble the first 32 letters for security reasons.
260
261 Note the two names are guaranteed to be the same length and differ only in the case
262 of letters at this point.
263
264 The original query we sent is now in packet buffer and the query name in the
265 new instance is on daemon->namebuff. */
266
267 if (extract_name(header, forward->stash_len, NULL, daemon->workspacename, EXTR_NAME_EXTRACT, 0))
268 {
269 unsigned int i, gobig = 0;
270 char *s1, *s2;
271
272 #define BITS_IN_INT (sizeof(unsigned int) * 8)
273
274 big_redo:
275 for (s1 = daemon->namebuff, s2 = daemon->workspacename, i = 0; *s1; s1++, s2++)
276 {
277 char c1 = *s1, c2 = *s2;
278
279 if ((c1 >= 'a' && c1 <= 'z') || (c1 >= 'A' && c1 <= 'Z'))
280 {
281 if ((c1 & 0x20) ^ (c2 & 0x20))
282 {
283 if (bitvector)
284 bitvector[i/BITS_IN_INT] |= 1<<(i%BITS_IN_INT);
285 else if (i >= BITS_IN_INT)
286 gobig = 1; /* More than 32 */
287 else
288 casediff |= 1<<i;
289 }
290 i++;
291 }
292 }
293
294 if (gobig && !bitvector)
295 {
296 casediff = ((i - 1)/BITS_IN_INT) + 1; /* length of array */
297 /* whine_malloc() zeros memory */
298 if ((bitvector = whine_malloc(casediff * sizeof(unsigned int))))
299 goto big_redo;
300 }
301 }
302
303 src = daemon->free_frec_src;
304 daemon->free_frec_src = src->next;
305 src->next = forward->frec_src.next;
306 forward->frec_src.next = src;
307 src->orig_id = id;
308 src->source = *udpaddr;
309 src->dest = *dst_addr;
310 src->log_id = daemon->log_id;
311 src->iface = dst_iface;
312 src->fd = udpfd;
313 src->encode_bitmap = casediff;
314 src->encode_bigmap = bitvector;
315
316 src->udp_pkt_size = (unsigned short)replylimit;
317
318 /* closely spaced identical queries cannot be a try and a retry, so
319 it's safe to wait for the reply from the first without
320 forwarding the second. */
321 if (difftime(now, forward->time) < 2)
322 return;
323 }
324
325 /* use our id when resending */
326 header->id = ntohs(forward->new_id);
327 }
328
329 /* new query */
330 if (!forward)
331 {
332 if (OPCODE(header) != QUERY)
333 {
334 flags = F_RCODE;
335 goto reply;
336 }
337 else if (!gotname)
338 {
339 /* If the query is malformed, we can't forward it because
340 we can't recognise the answer. */
341 flags = 0;
342 ede = EDE_INVALID_DATA;
343 goto reply;
344 }
345
346 if (lookup_domain(daemon->namebuff, gotname, &first, &last))
347 flags = is_local_answer(now, first, daemon->namebuff);
348 else
349 {
350 /* no available server. */
351 ede = EDE_NOT_READY;
352 flags = 0;
353 }
354
355 /* don't forward A or AAAA queries for simple names, except the empty name */
356 if (!flags &&
357 option_bool(OPT_NODOTS_LOCAL) &&
358 (gotname & (F_IPV4 | F_IPV6)) &&
359 !strchr(daemon->namebuff, '.') &&
360 strlen(daemon->namebuff) != 0)
361 flags = check_for_local_domain(daemon->namebuff, now) ? F_NOERR : F_NXDOMAIN;
362
363 /* Configured answer. */
364 if (flags || ede == EDE_NOT_READY)
365 goto reply;
366
367 master = daemon->serverarray[first];
368
369 if (!(forward = get_new_frec(now, master, 0)))
370 goto reply;
371 /* table full - flags == 0, return REFUSED */
372
373 forward->flags = fwd_flags;
374
375 #ifdef HAVE_DNSSEC
376 if (option_bool(OPT_DNSSEC_VALID))
377 {
378 plen = add_do_bit(header, plen, daemon->edns_pktsz);
379
380 /* For debugging, set Checking Disabled, otherwise, have the upstream check too,
381 this allows it to select auth servers when one is returning bad data. */
382 if (option_bool(OPT_DNSSEC_DEBUG))
383 header->hb4 |= HB4_CD;
384 }
385 #endif
386
387 /* Do these before saving query. */
388 forward->frec_src.orig_id = ntohs(header->id);
389 forward->new_id = get_id();
390 header->id = ntohs(forward->new_id);
391 forward->frec_src.encode_bitmap = (!option_bool(OPT_NO_0x20) && option_bool(OPT_DO_0x20)) ? rand32() : 0;
392 forward->frec_src.encode_bigmap = NULL;
393
394 if (!extract_name(header, plen, NULL, (char *)&forward->frec_src.encode_bitmap, EXTR_NAME_FLIP, 1))
395 goto reply;
396
397 /* Keep copy of query for retries and move to TCP */
398 if (!(forward->stash = blockdata_alloc((char *)header, plen)))
399 {
400 free_frec(forward);
401 goto reply; /* no mem. return REFUSED */
402 }
403
404 forward->stash_len = plen;
405 forward->frec_src.log_id = daemon->log_id;
406 forward->frec_src.source = *udpaddr;
407 forward->frec_src.dest = *dst_addr;
408 forward->frec_src.iface = dst_iface;
409 forward->frec_src.next = NULL;
410 forward->frec_src.fd = udpfd;
411 forward->frec_src.udp_pkt_size = (unsigned short)replylimit;
412 forward->forwardall = 0;
413 if (domain_no_rebind(daemon->namebuff))
414 forward->flags |= FREC_NOREBIND;
415 #ifdef HAVE_DNSSEC
416 forward->work_counter = daemon->limit[LIMIT_WORK];
417 forward->validate_counter = daemon->limit[LIMIT_CRYPTO];
418 #endif
419
420 start = first;
421
422 if (option_bool(OPT_ALL_SERVERS))
423 forward->forwardall = 1;
424
425 if (!option_bool(OPT_ORDER))
426 {
427 if (master->forwardcount++ > FORWARD_TEST ||
428 difftime(now, master->forwardtime) > FORWARD_TIME ||
429 master->last_server == -1)
430 {
431 master->forwardtime = now;
432 master->forwardcount = 0;
433 forward->forwardall = 1;
434 }
435 else
436 start = master->last_server;
437 }
438 }
439 else
440 {
441 #ifdef HAVE_DNSSEC
442 /* If we've already got an answer to this query, but we're awaiting keys for validation,
443 there's no point retrying the query, retry the key query instead...... */
444 while (forward->blocking_query)
445 forward = forward->blocking_query;
446
447 /* Don't retry if we've already sent it via TCP. */
448 if (forward->flags & FREC_GONE_TO_TCP)
449 return;
450
451 if (forward->flags & (FREC_DNSKEY_QUERY | FREC_DS_QUERY))
452 {
453 /* log_id should match previous DNSSEC query. */
454 daemon->log_display_id = forward->frec_src.log_id;
455
456 blockdata_retrieve(forward->stash, forward->stash_len, (void *)header);
457 plen = forward->stash_len;
458 /* get query for logging. */
459 gotname = extract_request(header, plen, daemon->namebuff, NULL, NULL);
460
461 /* Find suitable servers: should never fail. */
462 if (!filter_servers(forward->sentto->arrayposn, F_DNSSECOK, &first, &last))
463 return;
464
465 is_dnssec = 1;
466 forward->forwardall = 1;
467 }
468 else
469 #endif
470 {
471 /* retry on existing query, from original source. Send to all available servers */
472 if (udpfd == -1 && !fast_retry)
473 forward->sentto->failed_queries++;
474 else
475 forward->sentto->retrys++;
476
477 if (!filter_servers(forward->sentto->arrayposn, F_SERVER, &first, &last))
478 goto reply;
479
480 master = daemon->serverarray[first];
481
482 /* Forward to all available servers on retry of query from same host. */
483 if (!option_bool(OPT_ORDER) && old_src && !fast_retry)
484 forward->forwardall = 1;
485 else
486 {
487 start = forward->sentto->arrayposn;
488
489 if (option_bool(OPT_ORDER) && !fast_retry)
490 {
491 /* In strict order mode, there must be a server later in the list
492 left to send to, otherwise without the forwardall mechanism,
493 code further on will cycle around the list forwever if they
494 all return REFUSED. If at the last, give up.
495 Note that we can get here EITHER because a client retried,
496 or an upstream server returned REFUSED. The above only
497 applied in the later case. For client retries,
498 keep trying the last server.. */
499 if (++start == last)
500 {
501 if (old_reply)
502 goto reply;
503 else
504 start--;
505 }
506 }
507 }
508 }
509 }
510
511 if (forward->forwardall)
512 start = first;
513
514 forwarded = 0;
515
516 /* Advertise the size of UDP reply we can accept. */
517 plen = add_pseudoheader(header, plen, daemon->edns_pktsz, 0, NULL, 0, 0, 0);
518
519 /* check for send errors here (no route to host)
520 if we fail to send to all nameservers, send back an error
521 packet straight away (helps modem users when offline) */
522
523 while (1)
524 {
525 int fd;
526 struct server *srv = daemon->serverarray[start];
527
528 if ((fd = allocate_rfd(&forward->rfds, srv)) != -1)
529 {
530
531 #ifdef HAVE_CONNTRACK
532 /* Copy connection mark of incoming query to outgoing connection. */
533 if (option_bool(OPT_CONNTRACK))
534 set_outgoing_mark(forward, fd);
535 #endif
536 if (retry_send(sendto(fd, (char *)header, plen, 0,
537 &srv->addr.sa,
538 sa_len(&srv->addr))))
539 continue;
540
541 if (errno == 0)
542 {
543 #ifdef HAVE_DUMPFILE
544 dump_packet_udp(DUMP_UP_QUERY, (void *)header, plen, NULL, &srv->addr, fd);
545 #endif
546
547 /* Keep info in case we want to re-send this packet */
548 daemon->srv_save = srv;
549 daemon->packet_len = plen;
550 daemon->fd_save = fd;
551
552 if (!gotname)
553 strcpy(daemon->namebuff, "query");
554
555 if (!(forward->flags & (FREC_DNSKEY_QUERY | FREC_DS_QUERY)))
556 log_query_mysockaddr(F_SERVER | F_FORWARD, daemon->namebuff,
557 &srv->addr, NULL, 0);
558 #ifdef HAVE_DNSSEC
559 else
560 log_query_mysockaddr(F_NOEXTRA | F_DNSSEC | F_SERVER, daemon->namebuff, &srv->addr,
561 (forward->flags & FREC_DNSKEY_QUERY) ? "dnssec-retry[DNSKEY]" : "dnssec-retry[DS]", 0);
562 #endif
563
564 srv->queries++;
565 forwarded = 1;
566 forward->sentto = srv;
567 if (!forward->forwardall)
568 break;
569 forward->forwardall++;
570 }
571 }
572
573 if (++start == last)
574 break;
575 }
576
577 if (forwarded || is_dnssec)
578 {
579 daemon->metrics[METRIC_DNS_QUERIES_FORWARDED]++;
580 forward->forward_timestamp = dnsmasq_milliseconds();
581 return;
582 }
583
584 /* could not send on, prepare to return */
585 header->id = htons(forward->frec_src.orig_id);
586 free_frec(forward); /* cancel */
587 ede = EDE_NETERR;
588
589 reply:
590 if (udpfd != -1)
591 {
592 if (!(plen = make_local_answer(flags, gotname, plen, header, daemon->namebuff, replylimit, first, last, ede)))
593 return;
594
595 if (fwd_flags & FREC_HAS_PHEADER)
596 {
597 u16 swap = htons((u16)ede);
598
599 if (ede != EDE_UNSET)
600 plen = add_pseudoheader(header, plen, replylimit, EDNS0_OPTION_EDE, (unsigned char *)&swap, 2, 0, 0);
601 else
602 plen = add_pseudoheader(header, plen, replylimit, 0, NULL, 0, 0, 0);
603 }
604
605 #if defined(HAVE_CONNTRACK) && defined(HAVE_UBUS)
606 if (option_bool(OPT_CMARK_ALST_EN))
607 {
608 unsigned int mark;
609 int have_mark = get_incoming_mark(udpaddr, dst_addr, /* istcp: */ 0, &mark);
610 if (have_mark && ((u32)mark & daemon->allowlist_mask))
611 report_addresses(header, plen, mark);
612 }
613 #endif
614
615 #ifdef HAVE_DUMPFILE
616 dump_packet_udp(DUMP_REPLY, (void *)header, plen, NULL, udpaddr, udpfd);
617 #endif
618 send_from(udpfd, option_bool(OPT_NOWILD) || option_bool(OPT_CLEVERBIND), (char *)header, plen, udpaddr, dst_addr, dst_iface);
619 }
620
621 daemon->metrics[METRIC_DNS_LOCAL_ANSWERED]++;
622 return;
623 }
624
625 /* Check if any frecs need to do a retry, and action that if so.
626 Return time in milliseconds until he next retry will be required,
627 or -1 if none. */
628 int fast_retry(time_t now)
629 {
630 struct frec *f;
631 int ret = -1;
632
633 if (daemon->fast_retry_time != 0)
634 {
635 u32 millis = dnsmasq_milliseconds();
636
637 for (f = daemon->frec_list; f; f = f->next)
638 if (f->sentto && difftime(now, f->time) < daemon->fast_retry_timeout)
639 {
640 #ifdef HAVE_DNSSEC
641 if (f->blocking_query || (f->flags & FREC_GONE_TO_TCP))
642 continue;
643 #endif
644 /* t is milliseconds since last query sent. */
645 int to_run, t = (int)(millis - f->forward_timestamp);
646
647 if (t < f->forward_delay)
648 to_run = f->forward_delay - t;
649 else
650 {
651 struct dns_header *header = (struct dns_header *)daemon->packet;
652
653 /* packet buffer overwritten */
654 daemon->srv_save = NULL;
655
656 blockdata_retrieve(f->stash, f->stash_len, (void *)header);
657
658 daemon->log_display_id = f->frec_src.log_id;
659 daemon->log_source_addr = NULL;
660
661 forward_query(-1, NULL, NULL, 0, header, f->stash_len, 0, now, f, 0, 1);
662
663 to_run = f->forward_delay = 2 * f->forward_delay;
664 }
665
666 if (ret == -1 || ret > to_run)
667 ret = to_run;
668 }
669 }
670 return ret;
671 }
672
673 #if defined(HAVE_IPSET) || defined(HAVE_NFTSET)
674 static struct ipsets *domain_find_sets(struct ipsets *setlist, const char *domain) {
675 /* Similar algorithm to search_servers. */
676 struct ipsets *ipset_pos, *ret = NULL;
677 unsigned int namelen = strlen(domain);
678 unsigned int matchlen = 0;
679 for (ipset_pos = setlist; ipset_pos; ipset_pos = ipset_pos->next)
680 {
681 unsigned int domainlen = strlen(ipset_pos->domain);
682 const char *matchstart = domain + namelen - domainlen;
683 if (namelen >= domainlen && hostname_isequal(matchstart, ipset_pos->domain) &&
684 (domainlen == 0 || namelen == domainlen || *(matchstart - 1) == '.' ) &&
685 domainlen >= matchlen)
686 {
687 matchlen = domainlen;
688 ret = ipset_pos;
689 }
690 }
691
692 return ret;
693 }
694 #endif
695
696 static size_t process_reply(struct dns_header *header, time_t now, struct server *server, size_t n, int check_rebind,
697 int no_cache, int cache_secure, int bogusanswer, int ad_reqd, int do_bit, int added_pheader,
698 union mysockaddr *query_source, size_t outlen, int ede)
699 {
700 unsigned char *pheader, *sizep;
701 struct ipsets *ipsets = NULL, *nftsets = NULL;
702 int is_sign;
703 unsigned int rcode = RCODE(header);
704 size_t plen;
705
706 (void)ad_reqd;
707 (void)do_bit;
708
709 #if defined(HAVE_IPSET) || defined(HAVE_NFTSET)
710 if ((daemon->ipsets || daemon->nftsets) && extract_name(header, n, NULL, daemon->namebuff, EXTR_NAME_EXTRACT, 0))
711 {
712 # ifdef HAVE_IPSET
713 ipsets = domain_find_sets(daemon->ipsets, daemon->namebuff);
714 # endif
715
716 # ifdef HAVE_NFTSET
717 nftsets = domain_find_sets(daemon->nftsets, daemon->namebuff);
718 # endif
719 }
720 #endif
721
722 if ((pheader = find_pseudoheader(header, n, &plen, &sizep, &is_sign, NULL)))
723 {
724 /* Get extended RCODE. */
725 rcode |= sizep[2] << 4;
726
727 if (option_bool(OPT_CLIENT_SUBNET) && !check_source(header, n, pheader, query_source))
728 {
729 my_syslog(LOG_WARNING, _("discarding DNS reply: subnet option mismatch"));
730 return 0;
731 }
732
733 if (!is_sign)
734 {
735 if (added_pheader)
736 {
737 /* client didn't send EDNS0, we added one, strip it off before returning answer. */
738 rrfilter(header, &n, RRFILTER_EDNS0);
739 pheader = NULL;
740 }
741 else
742 {
743 /* Advertise our max UDP packet to the client. */
744 PUTSHORT(daemon->edns_pktsz, sizep);
745
746 #ifdef HAVE_DNSSEC
747 /* If the client didn't set the do bit, but we did, reset it. */
748 if (option_bool(OPT_DNSSEC_VALID) && !do_bit)
749 {
750 unsigned short flags;
751 sizep += 2; /* skip RCODE */
752 GETSHORT(flags, sizep);
753 flags &= ~0x8000;
754 sizep -= 2;
755 PUTSHORT(flags, sizep);
756 }
757 #endif
758 }
759 }
760 }
761
762 /* RFC 4035 sect 4.6 para 3 */
763 if (!is_sign && !option_bool(OPT_DNSSEC_PROXY))
764 header->hb4 &= ~HB4_AD;
765
766 /* Complain loudly if the upstream server is non-recursive. */
767 if (!(header->hb4 & HB4_RA) && rcode == NOERROR &&
768 server && !(server->flags & SERV_WARNED_RECURSIVE))
769 {
770 (void)prettyprint_addr(&server->addr, daemon->namebuff);
771 my_syslog(LOG_WARNING, _("nameserver %s refused to do a recursive query"), daemon->namebuff);
772 if (!option_bool(OPT_LOG))
773 server->flags |= SERV_WARNED_RECURSIVE;
774 }
775
776 header->hb4 |= HB4_RA; /* recursion if available */
777
778 if (OPCODE(header) != QUERY)
779 return resize_packet(header, n, pheader, plen);
780
781 if (rcode != NOERROR && rcode != NXDOMAIN)
782 {
783 union all_addr a;
784 a.log.rcode = rcode;
785 a.log.ede = ede;
786 log_query(F_UPSTREAM | F_RCODE, "error", &a, NULL, 0);
787
788 return resize_packet(header, n, pheader, plen);
789 }
790
791 if (header->hb3 & HB3_TC)
792 log_query(F_UPSTREAM, NULL, NULL, "truncated", 0);
793 else if (!bogusanswer || (header->hb4 & HB4_CD))
794 {
795 if (rcode == NXDOMAIN && extract_name(header, n, NULL, daemon->namebuff, EXTR_NAME_EXTRACT, 0) &&
796 (check_for_local_domain(daemon->namebuff, now) || lookup_domain(daemon->namebuff, F_CONFIG, NULL, NULL)))
797 {
798 /* if we forwarded a query for a locally known name (because it was for
799 an unknown type) and the answer is NXDOMAIN, convert that to NODATA,
800 since we know that the domain exists, even if upstream doesn't */
801 header->hb3 |= HB3_AA;
802 SET_RCODE(header, NOERROR);
803 cache_secure = 0;
804 }
805
806 if (daemon->doctors && do_doctor(header, n, daemon->namebuff))
807 cache_secure = 0;
808
809 /* check_for_bogus_wildcard() does its own caching, so
810 don't call extract_addresses() if it triggers. */
811 if (daemon->bogus_addr && rcode != NXDOMAIN &&
812 check_for_bogus_wildcard(header, n, daemon->namebuff, now))
813 {
814 header->ancount = htons(0);
815 header->nscount = htons(0);
816 header->arcount = htons(0);
817 SET_RCODE(header, NXDOMAIN);
818 header->hb3 &= ~HB3_AA;
819 cache_secure = 0;
820 ede = EDE_BLOCKED;
821 }
822 else
823 {
824 int rc = extract_addresses(header, n, daemon->namebuff, now, ipsets, nftsets, check_rebind, no_cache, cache_secure);
825
826 if (rc != 0)
827 {
828 header->ancount = htons(0);
829 header->nscount = htons(0);
830 header->arcount = htons(0);
831 cache_secure = 0;
832 }
833
834 if (rc == 1)
835 {
836 my_syslog(LOG_WARNING, _("possible DNS-rebind attack detected: %s"), daemon->namebuff);
837 ede = EDE_BLOCKED;
838 }
839
840 if (rc == 2)
841 {
842 /* extract_addresses() found a malformed answer. */
843 SET_RCODE(header, SERVFAIL);
844 ede = EDE_OTHER;
845 }
846 }
847
848 if (RCODE(header) == NOERROR && rrfilter(header, &n, RRFILTER_CONF) > 0)
849 ede = EDE_FILTERED;
850 }
851
852 #ifdef HAVE_DNSSEC
853 if (option_bool(OPT_DNSSEC_VALID))
854 {
855 if (bogusanswer)
856 {
857 if (!(header->hb4 & HB4_CD) && !option_bool(OPT_DNSSEC_DEBUG))
858 {
859 /* Bogus reply, turn into SERVFAIL */
860 SET_RCODE(header, SERVFAIL);
861 header->ancount = htons(0);
862 header->nscount = htons(0);
863 header->arcount = htons(0);
864 }
865 }
866 else if (ad_reqd && cache_secure)
867 header->hb4 |= HB4_AD;
868
869 /* If the requestor didn't set the DO bit, don't return DNSSEC info. */
870 if (!do_bit)
871 rrfilter(header, &n, RRFILTER_DNSSEC);
872 }
873 #endif
874
875 /* the code above can elide sections of the packet. Find the new length here
876 and put back pseudoheader if it was removed. */
877 n = resize_packet(header, n, pheader, plen);
878
879 if (pheader && ede != EDE_UNSET)
880 {
881 u16 swap = htons((u16)ede);
882 n = add_pseudoheader(header, n, outlen, EDNS0_OPTION_EDE, (unsigned char *)&swap, 2, do_bit, 1);
883 }
884
885 if (RCODE(header) == NXDOMAIN)
886 server->nxdomain_replies++;
887
888 return n;
889 }
890
891 #ifdef HAVE_DNSSEC
892 static void dnssec_validate(struct frec *forward, struct dns_header *header,
893 ssize_t plen, int status, time_t now)
894 {
895 struct frec *orig;
896 int log_resource = 0;
897
898 daemon->log_display_id = forward->frec_src.log_id;
899
900 /* Find the original query that started it all.... */
901 for (orig = forward; orig->dependent; orig = orig->dependent);
902
903 /* As soon as anything returns BOGUS, we stop and unwind, to do otherwise
904 would invite infinite loops, since the answers to DNSKEY and DS queries
905 will not be cached, so they'll be repeated. */
906 if (!STAT_ISEQUAL(status, STAT_BOGUS) && !STAT_ISEQUAL(status, STAT_TRUNCATED) && !STAT_ISEQUAL(status, STAT_ABANDONED))
907 {
908 /* If all replies to a query are REFUSED, give up. */
909 if (RCODE(header) == REFUSED)
910 status = STAT_ABANDONED;
911 else if (header->hb3 & HB3_TC)
912 {
913 /* Truncated answer can't be validated.
914 If this is an answer to a DNSSEC-generated query, we
915 switch to TCP mode. For downstream queries, if the client didn't ask for
916 DNSSEC RRs, do the query over TCP, and hope that it fits once the DNSSEC RRs
917 have been stripped, otherwise get the client
918 to retry over TCP, so return an answer with the TC bit set. */
919 if ((forward->flags & (FREC_DNSKEY_QUERY | FREC_DS_QUERY)) || !(forward->flags & FREC_DO_QUESTION))
920 {
921 status = (forward->flags & FREC_DNSKEY_QUERY) ? STAT_NEED_KEY:
922 ((forward->flags & FREC_DS_QUERY) ? STAT_NEED_DS : STAT_OK);
923
924 /* Get the query we sent by UDP */
925 blockdata_retrieve(forward->stash, forward->stash_len, (void *)header);
926
927 if (!extract_name(header, forward->stash_len, NULL, daemon->namebuff, EXTR_NAME_EXTRACT, 0))
928 status = STAT_ABANDONED;
929 else
930 {
931 log_query(F_UPSTREAM | F_NOEXTRA, daemon->namebuff, NULL, "truncated", 0);
932
933 /* Don't count failed UDP attempt AND TCP */
934 if (status != STAT_OK)
935 orig->work_counter++;
936
937 /* NOTE: Can't move connection marks from UDP to TCP */
938 plen = forward->stash_len;
939 status = swap_to_tcp(forward, now, status, header, &plen, daemon->namebuff, forward->class, forward->sentto, &orig->work_counter, &orig->validate_counter);
940
941 /* We forked a new process. pop_and_retry_query() will be called when is completes. */
942 if (STAT_ISEQUAL(status, STAT_ASYNC))
943 {
944 forward->flags |= FREC_GONE_TO_TCP;
945 return;
946 }
947 }
948 }
949 else
950 status = STAT_TRUNCATED;
951 }
952 else
953 {
954 /* As soon as anything returns BOGUS, we stop and unwind, to do otherwise
955 would invite infinite loops, since the answers to DNSKEY and DS queries
956 will not be cached, so they'll be repeated. */
957 ds_retry:
958 if (forward->flags & FREC_DNSKEY_QUERY)
959 status = dnssec_validate_by_ds(now, header, plen, daemon->namebuff, daemon->keyname, forward->class, &orig->validate_counter);
960 else if (forward->flags & FREC_DS_QUERY)
961 status = dnssec_validate_ds(now, header, plen, daemon->namebuff, daemon->keyname, forward->class, &orig->validate_counter);
962 else
963 status = dnssec_validate_reply(now, header, plen, daemon->namebuff, daemon->keyname, &forward->class,
964 !option_bool(OPT_DNSSEC_IGN_NS), NULL, NULL, NULL, NULL, &orig->validate_counter);
965
966 if (STAT_ISEQUAL(status, STAT_ABANDONED))
967 log_resource = 1;
968 }
969 }
970
971 /* Can't validate, as we're missing key data. Put this
972 answer aside, whilst we get that. */
973 if (STAT_ISEQUAL(status, STAT_NEED_DS) || STAT_ISEQUAL(status, STAT_NEED_KEY))
974 {
975 struct blockdata *stash;
976
977 /* Now save reply pending receipt of key data */
978 if ((stash = blockdata_alloc((char *)header, plen)))
979 {
980 /* validate routines leave name of required record in daemon->keyname */
981 unsigned int flags = STAT_ISEQUAL(status, STAT_NEED_KEY) ? FREC_DNSKEY_QUERY : FREC_DS_QUERY;
982 struct frec *old;
983
984 if ((old = lookup_frec(now, daemon->keyname, forward->class, -1, -1, flags, flags)))
985 {
986 /* This is tricky; it detects loops in the dependency
987 graph for DNSSEC validation, say validating A requires DS B
988 and validating DS B requires DNSKEY C and validating DNSKEY C requires DS B.
989 This should never happen in correctly signed records, but it's
990 likely the case that sufficiently broken ones can cause our validation
991 code requests to exhibit cycles. The result is that the ->blocking_query list
992 can form a cycle, and under certain circumstances that can lock us in
993 an infinite loop. Here we transform the situation into ABANDONED. */
994 struct frec *f;
995 for (f = old; f; f = f->blocking_query)
996 if (f == forward)
997 break;
998
999 if (!f)
1000 {
1001 forward->next_dependent = old->dependent;
1002 old->dependent = forward;
1003 /* Make consistent, only replace query copy with unvalidated answer
1004 when we set ->blocking_query. */
1005 blockdata_free(forward->stash);
1006 forward->blocking_query = old;
1007 forward->stash_len = plen;
1008 forward->stash = stash;
1009 return;
1010 }
1011 }
1012 else if (orig->work_counter-- == 0)
1013 {
1014 my_syslog(LOG_WARNING, _("limit exceeded: per-query subqueries"));
1015 log_resource = 1;
1016 }
1017 else
1018 {
1019 struct server *server;
1020 size_t nn;
1021 int serverind, fd;
1022 struct randfd_list *rfds = NULL;
1023 struct frec *new = NULL;
1024 struct blockdata *newstash = NULL;
1025
1026 /* Make sure we don't expire and free the orig frec during the
1027 allocation of a new one: third arg of get_new_frec() does that. */
1028 if ((serverind = dnssec_server(forward->sentto, daemon->keyname, STAT_ISEQUAL(status, STAT_NEED_DS), NULL, NULL)) != -1 &&
1029 (server = daemon->serverarray[serverind]) &&
1030 (nn = dnssec_generate_query(header, daemon->edns_pktsz,
1031 daemon->keyname, forward->class, get_id(),
1032 STAT_ISEQUAL(status, STAT_NEED_KEY) ? T_DNSKEY : T_DS)) &&
1033 (fd = allocate_rfd(&rfds, server)) != -1 &&
1034 (newstash = blockdata_alloc((char *)header, nn)) &&
1035 (new = get_new_frec(now, server, 1)))
1036 {
1037 struct frec *next = new->next;
1038
1039 *new = *forward; /* copy everything, then overwrite */
1040 new->next = next;
1041 new->blocking_query = NULL;
1042
1043 new->frec_src.log_id = daemon->log_display_id = ++daemon->log_id;
1044 new->sentto = server;
1045 new->rfds = rfds;
1046 new->frec_src.next = NULL;
1047 new->flags &= ~(FREC_DNSKEY_QUERY | FREC_DS_QUERY);
1048 new->flags |= flags;
1049 new->forwardall = 0;
1050 new->frec_src.encode_bitmap = 0;
1051 new->frec_src.encode_bigmap = NULL;
1052
1053 forward->next_dependent = NULL;
1054 new->dependent = forward; /* to find query awaiting new one. */
1055
1056 /* Make consistent, only replace query copy with unvalidated answer
1057 when we set ->blocking_query. */
1058 forward->blocking_query = new;
1059 blockdata_free(forward->stash);
1060 forward->stash_len = plen;
1061 forward->stash = stash;
1062
1063 new->new_id = ntohs(header->id);
1064 /* Save query for retransmission and de-dup */
1065 new->stash = newstash;
1066 new->stash_len = nn;
1067 if (daemon->fast_retry_time != 0)
1068 new->forward_timestamp = dnsmasq_milliseconds();
1069
1070 /* Don't resend this. */
1071 daemon->srv_save = NULL;
1072
1073 #ifdef HAVE_CONNTRACK
1074 if (option_bool(OPT_CONNTRACK))
1075 set_outgoing_mark(orig, fd);
1076 #endif
1077
1078 server_send(server, fd, header, nn);
1079 server->queries++;
1080 #ifdef HAVE_DUMPFILE
1081 dump_packet_udp(DUMP_SEC_QUERY, (void *)header, (size_t)nn, NULL, &server->addr, fd);
1082 #endif
1083 log_query_mysockaddr(F_NOEXTRA | F_DNSSEC | F_SERVER, daemon->keyname, &server->addr,
1084 STAT_ISEQUAL(status, STAT_NEED_KEY) ? "dnssec-query[DNSKEY]" : "dnssec-query[DS]", 0);
1085 return;
1086 }
1087
1088 /* If there's no server for the parent of a domain-specific server's domain,
1089 assume that said server's contents it legitimately unsigned, as if the parent
1090 contained a negative DS record. This is part of the same logic that's found
1091 in dnssec_validate_ds() when it gets a negative DS repsonse. */
1092 if (STAT_ISEQUAL(status, STAT_NEED_DS) && serverind == -1 && lookup_domain(daemon->keyname, F_DOMAINSRV, NULL, NULL) &&
1093 cache_neg_ds(daemon->keyname, F_FORWARD | F_DS | F_NEG | F_DNSSECOK, forward->class, now, DNSSEC_ASSUMED_DS_TTL) == STAT_OK)
1094 {
1095 my_syslog(LOG_WARNING, _("no server for parent domain of %s, assuming unsigned domain"), daemon->keyname);
1096 blockdata_free(stash);
1097 goto ds_retry;
1098 }
1099
1100 /* error unwind */
1101 free_rfds(&rfds);
1102 blockdata_free(newstash);
1103 }
1104
1105 blockdata_free(stash); /* don't leak this on failure. */
1106 }
1107
1108 /* sending DNSSEC query failed or loop detected. */
1109 status = STAT_ABANDONED;
1110 }
1111
1112 if (log_resource)
1113 {
1114 /* Log the actual validation that made us barf. */
1115 if (extract_name(header, plen, NULL, daemon->namebuff, EXTR_NAME_EXTRACT, 0))
1116 my_syslog(LOG_WARNING, _("validation of %s failed: resource limit exceeded."),
1117 daemon->namebuff[0] ? daemon->namebuff : ".");
1118 }
1119
1120 #ifdef HAVE_DUMPFILE
1121 if (STAT_ISEQUAL(status, STAT_BOGUS) || STAT_ISEQUAL(status, STAT_ABANDONED))
1122 dump_packet_udp((forward->flags & (FREC_DNSKEY_QUERY | FREC_DS_QUERY)) ? DUMP_SEC_BOGUS : DUMP_BOGUS,
1123 header, (size_t)plen, &forward->sentto->addr, NULL, -daemon->port);
1124 #endif
1125
1126 if (!forward->dependent)
1127 /* Validated original answer, all done. */
1128 return_reply(now, forward, header, plen, status);
1129 else
1130 pop_and_retry_query(forward, status, now);
1131 }
1132
1133 void pop_and_retry_query(struct frec *forward, int status, time_t now)
1134 {
1135 /* validated subsidiary query/queries, (and cached result)
1136 pop that and return to the previous query/queries we were working on. */
1137 struct frec *prev, *nxt = forward->dependent;
1138 struct dns_header *header = (struct dns_header *)daemon->packet;
1139
1140 free_frec(forward);
1141
1142 while ((prev = nxt))
1143 {
1144 /* ->next_dependent will have changed after return from recursive call below. */
1145 nxt = prev->next_dependent;
1146 prev->blocking_query = NULL; /* already gone */
1147 blockdata_retrieve(prev->stash, prev->stash_len, (void *)header);
1148 dnssec_validate(prev, header, prev->stash_len, status, now);
1149 }
1150 }
1151 #endif
1152
1153 /* sets new last_server */
1154 void reply_query(int fd, time_t now)
1155 {
1156 /* packet from peer server, extract data for cache, and send to
1157 original requester */
1158 struct dns_header *header;
1159 union mysockaddr serveraddr;
1160 struct frec *forward;
1161 socklen_t addrlen = sizeof(serveraddr);
1162 ssize_t n = recvfrom(fd, daemon->packet, daemon->packet_buff_sz, 0, &serveraddr.sa, &addrlen);
1163 struct server *server;
1164 int first, last, serv, c, class, rrtype;
1165 unsigned char *p;
1166 struct randfd_list *fdl;
1167
1168 /* packet buffer overwritten */
1169 daemon->srv_save = NULL;
1170
1171 /* Determine the address of the server replying so that we can mark that as good */
1172 if (serveraddr.sa.sa_family == AF_INET6)
1173 serveraddr.in6.sin6_flowinfo = 0;
1174
1175 header = (struct dns_header *)daemon->packet;
1176
1177 if (n < (int)sizeof(struct dns_header) || !(header->hb3 & HB3_QR) || ntohs(header->qdcount) != 1)
1178 return;
1179
1180 p = (unsigned char *)(header+1);
1181 if (!extract_name(header, n, &p, daemon->namebuff, EXTR_NAME_EXTRACT, 4))
1182 return; /* bad packet */
1183 GETSHORT(rrtype, p);
1184 GETSHORT(class, p);
1185
1186 if (!(forward = lookup_frec(now, daemon->namebuff, class, rrtype, ntohs(header->id), FREC_ANSWER, 0)))
1187 return;
1188
1189 filter_servers(forward->sentto->arrayposn, F_SERVER, &first, &last);
1190
1191 /* Check that this arrived on the file descriptor we expected. */
1192
1193 /* sent from random port */
1194 for (fdl = forward->rfds; fdl; fdl = fdl->next)
1195 if (fdl->rfd->fd == fd)
1196 break;
1197
1198 if (!fdl)
1199 {
1200 /* Sent to upstream from socket associated with a server.
1201 Note we have to iterate over all the possible servers, since they may
1202 have different bound sockets. */
1203 for (serv = first; serv != last; serv++)
1204 {
1205 server = daemon->serverarray[serv];
1206 if (server->sfd && server->sfd->fd == fd)
1207 break;
1208 }
1209
1210 if (serv == last)
1211 return;
1212 }
1213
1214 /* spoof check: answer must come from known server, also
1215 we may have sent the same query to multiple servers from
1216 the same local socket, and would like to know which one has answered. */
1217 for (c = first; c != last; c++)
1218 if (sockaddr_isequal(&daemon->serverarray[c]->addr, &serveraddr))
1219 break;
1220
1221 if (c == last)
1222 return;
1223
1224 server = daemon->serverarray[c];
1225
1226 if (RCODE(header) != REFUSED)
1227 daemon->serverarray[first]->last_server = c;
1228 else if (daemon->serverarray[first]->last_server == c)
1229 daemon->serverarray[first]->last_server = -1;
1230
1231 /* log_query gets called indirectly all over the place, so
1232 pass these in global variables - sorry. */
1233 daemon->log_display_id = forward->frec_src.log_id;
1234 daemon->log_source_addr = &forward->frec_src.source;
1235
1236 #ifdef HAVE_DUMPFILE
1237 dump_packet_udp((forward->flags & (FREC_DNSKEY_QUERY | FREC_DS_QUERY)) ? DUMP_SEC_REPLY : DUMP_UP_REPLY,
1238 (void *)header, n, &serveraddr, NULL, fd);
1239 #endif
1240
1241 if (daemon->ignore_addr && RCODE(header) == NOERROR &&
1242 check_for_ignored_address(header, n))
1243 return;
1244
1245 #ifdef HAVE_DNSSEC
1246 /* The query MAY have got a good answer, and be awaiting
1247 the results of further queries, in which case
1248 the stash contains something else and we don't need to retry anyway.
1249 We may also have already got a truncated reply, and be in the process
1250 of doing the query by TCP so can ignore further, probably truncated, UDP answers. */
1251 if (forward->blocking_query || (forward->flags & FREC_GONE_TO_TCP))
1252 return;
1253 #endif
1254
1255 if ((RCODE(header) == REFUSED || RCODE(header) == SERVFAIL) && forward->forwardall == 0)
1256 /* for broken servers, attempt to send to another one. */
1257 {
1258 /* Get the saved query back. */
1259 blockdata_retrieve(forward->stash, forward->stash_len, (void *)header);
1260
1261 forward_query(-1, NULL, NULL, 0, header, forward->stash_len, 0, now, forward, 0, 0);
1262 return;
1263 }
1264
1265 /* If the answer is an error, keep the forward record in place in case
1266 we get a good reply from another server. Kill it when we've
1267 had replies from all to avoid filling the forwarding table when
1268 everything is broken */
1269
1270 /* decrement count of replies recieved if we sent to more than one server. */
1271 if (forward->forwardall && (--forward->forwardall > 1) && RCODE(header) == REFUSED)
1272 return;
1273
1274 forward->sentto = server;
1275
1276 /* We have a good answer, and will now validate it or return it.
1277 It may be some time before this the validation completes, but we don't need
1278 any more answers, so close the socket(s) on which we were expecting
1279 answers, to conserve file descriptors, and to save work reading and
1280 discarding answers for other upstreams. */
1281 free_rfds(&forward->rfds);
1282
1283 /* calculate modified moving average of server latency */
1284 if (server->query_latency == 0)
1285 server->mma_latency = (dnsmasq_milliseconds() - forward->forward_timestamp) * 128; /* init */
1286 else
1287 server->mma_latency += dnsmasq_milliseconds() - forward->forward_timestamp - server->query_latency;
1288 /* denominator controls how many queries we average over. */
1289 server->query_latency = server->mma_latency/128;
1290
1291 /* Flip the bits back in the query name. */
1292 if (!extract_name(header, n, NULL, (char *)&forward->frec_src.encode_bitmap, EXTR_NAME_FLIP, 1))
1293 return;
1294
1295 #ifdef HAVE_DNSSEC
1296 if (option_bool(OPT_DNSSEC_VALID))
1297 {
1298 if (!(forward->flags & FREC_CHECKING_DISABLED))
1299 {
1300 dnssec_validate(forward, header, n, STAT_OK, now);
1301 return;
1302 }
1303
1304 /* If dnssec_validate() not called, rr_status{} is not valid
1305 Clear it so we don't erroneously mark RRs as secure using stale data from
1306 previous queries. */
1307 memset(daemon->rr_status, 0, sizeof(*daemon->rr_status) * daemon->rr_status_sz);
1308 }
1309 #endif
1310
1311 return_reply(now, forward, header, n, STAT_OK);
1312 }
1313
1314 static void xor_array(unsigned int *arg1, unsigned int *arg2, unsigned int len)
1315 {
1316 unsigned int i;
1317
1318 for (i = 0; i < len; i++)
1319 arg1[i] ^= arg2[i];
1320 }
1321
1322 /* Call extract_name() to flip case of query in packet according to the XOR of the bit maps help in arg1 and arg2 */
1323 static void flip_queryname(struct dns_header *header, ssize_t len, struct frec_src *arg1, struct frec_src *arg2)
1324 {
1325 unsigned int *arg1p, *arg2p, arg1len, arg2len;
1326
1327 /* Two cases: bitmap is single 32 bit int, or it's arbitrary-length array of 32bit ints.
1328 The two args may be different and of different lengths.
1329 The shorter gets notionally extended with zeros. */
1330
1331 if (arg1->encode_bigmap)
1332 arg1p = arg1->encode_bigmap, arg1len = arg1->encode_bitmap;
1333 else
1334 arg1p = &arg1->encode_bitmap, arg1len = 1;
1335
1336 if (arg2->encode_bigmap)
1337 arg2p = arg2->encode_bigmap, arg2len = arg2->encode_bitmap;
1338 else
1339 arg2p = &arg2->encode_bitmap, arg2len = 1;
1340
1341 /* make arg1 the longer, if they differ. */
1342 if (arg2len > arg1len)
1343 {
1344 unsigned int swapl = arg1len, *swapp = arg1p;
1345 arg1len = arg2len, arg1p = arg2p;
1346 arg2len = swapl, arg2p = swapp;
1347 }
1348
1349 /* XOR on shorter length, flip on longer, operate on longer */
1350 xor_array(arg1p, arg2p, arg2len);
1351 extract_name(header, len, NULL, (char *)arg1p, EXTR_NAME_FLIP, arg1len);
1352 xor_array(arg1p, arg2p, arg2len); /* restore */
1353 }
1354
1355 void return_reply(time_t now, struct frec *forward, struct dns_header *header, ssize_t n, int status)
1356 {
1357 int check_rebind = 0, no_cache_dnssec = 0, cache_secure = 0, bogusanswer = 0;
1358 size_t nn;
1359 int ede = EDE_UNSET;
1360
1361 (void)status;
1362
1363 daemon->log_display_id = forward->frec_src.log_id;
1364 daemon->log_source_addr = (forward->frec_src.fd != -1) ? &forward->frec_src.source : NULL;
1365
1366 /* Don't cache replies where DNSSEC validation was turned off, either
1367 the upstream server told us so, or the original query specified it. */
1368 if ((header->hb4 & HB4_CD) || (forward->flags & FREC_CHECKING_DISABLED))
1369 no_cache_dnssec = 1;
1370
1371 #ifdef HAVE_DNSSEC
1372 if (!STAT_ISEQUAL(status, STAT_OK))
1373 {
1374 /* status is STAT_OK when validation not turned on. */
1375 no_cache_dnssec = 0;
1376
1377 if (STAT_ISEQUAL(status, STAT_TRUNCATED))
1378 {
1379 header->hb3 |= HB3_TC;
1380 log_query(F_SECSTAT, "result", NULL, "TRUNCATED", 0);
1381 }
1382 else
1383 {
1384 char *result, *domain = "result";
1385 union all_addr a;
1386
1387 ede = errflags_to_ede(status);
1388
1389 if (STAT_ISEQUAL(status, STAT_ABANDONED))
1390 {
1391 result = "ABANDONED";
1392 status = STAT_BOGUS;
1393 if (ede == EDE_UNSET)
1394 ede = EDE_OTHER;
1395 }
1396 else
1397 result = (STAT_ISEQUAL(status, STAT_SECURE) ? "SECURE" : (STAT_ISEQUAL(status, STAT_INSECURE) ? "INSECURE" : "BOGUS"));
1398
1399
1400 if (STAT_ISEQUAL(status, STAT_SECURE))
1401 cache_secure = 1;
1402 else if (STAT_ISEQUAL(status, STAT_BOGUS))
1403 {
1404 if (ede == EDE_UNSET)
1405 ede = EDE_DNSSEC_BOGUS;
1406 no_cache_dnssec = 1;
1407 bogusanswer = 1;
1408
1409 if (extract_name(header, n, NULL, daemon->namebuff, EXTR_NAME_EXTRACT, 0))
1410 domain = daemon->namebuff;
1411 }
1412
1413 a.log.ede = ede;
1414 log_query(F_SECSTAT, domain, &a, result, 0);
1415
1416 if (ede == EDE_US_SERVFAIL)
1417 ede = EDE_DNSSEC_BOGUS;
1418 }
1419 }
1420
1421 if ((daemon->limit[LIMIT_CRYPTO] - forward->validate_counter) > (int)daemon->metrics[METRIC_CRYPTO_HWM])
1422 daemon->metrics[METRIC_CRYPTO_HWM] = daemon->limit[LIMIT_CRYPTO] - forward->validate_counter;
1423
1424 if ((daemon->limit[LIMIT_WORK] - forward->work_counter) > (int)daemon->metrics[METRIC_WORK_HWM])
1425 daemon->metrics[METRIC_WORK_HWM] = daemon->limit[LIMIT_WORK] - forward->work_counter;
1426 #endif
1427
1428 if (option_bool(OPT_NO_REBIND))
1429 check_rebind = !(forward->flags & FREC_NOREBIND);
1430
1431 /* restore CD bit to the value in the query */
1432 if (forward->flags & FREC_CHECKING_DISABLED)
1433 header->hb4 |= HB4_CD;
1434 else
1435 header->hb4 &= ~HB4_CD;
1436
1437 /* Never cache answers which are contingent on the source or MAC address EDSN0 option,
1438 since the cache is ignorant of such things. */
1439 if (forward->flags & FREC_NO_CACHE)
1440 no_cache_dnssec = 1;
1441
1442 if ((nn = process_reply(header, now, forward->sentto, (size_t)n, check_rebind, no_cache_dnssec, cache_secure, bogusanswer,
1443 forward->flags & FREC_AD_QUESTION, forward->flags & FREC_DO_QUESTION,
1444 !(forward->flags & FREC_HAS_PHEADER), &forward->frec_src.source,
1445 daemon->edns_pktsz, ede)))
1446 {
1447 struct frec_src *src, *prev;
1448 int do_trunc;
1449
1450 for (do_trunc = 0, prev = NULL, src = &forward->frec_src; src; prev = src, src = src->next)
1451 {
1452 header->id = htons(src->orig_id);
1453
1454 #if defined(HAVE_CONNTRACK) && defined(HAVE_UBUS)
1455 if (option_bool(OPT_CMARK_ALST_EN))
1456 {
1457 unsigned int mark;
1458 int have_mark = get_incoming_mark(&src->source, &src->dest, /* istcp: */ 0, &mark);
1459 if (have_mark && ((u32)mark & daemon->allowlist_mask))
1460 report_addresses(header, nn, mark);
1461 }
1462 #endif
1463
1464 /* You will have to draw diagrams and scratch your head to convince yourself
1465 that this works. Bear in mind that the flip to upstream state has already been undone,
1466 for the original query so nothing needs to be done, but subsequent queries' flips
1467 were recorded relative to the flipped name sent upstream. */
1468 if (prev)
1469 flip_queryname(header, nn, prev, src);
1470
1471 if (src->fd != -1)
1472 {
1473 /* Only send packets that fit what the requestor allows.
1474 We'll send a truncated packet to others below. */
1475 if (nn <= src->udp_pkt_size)
1476 {
1477 send_from(src->fd, option_bool(OPT_NOWILD) || option_bool (OPT_CLEVERBIND), daemon->packet, nn,
1478 &src->source, &src->dest, src->iface);
1479 #ifdef HAVE_DUMPFILE
1480 dump_packet_udp(DUMP_REPLY, daemon->packet, (size_t)nn, NULL, &src->source, src->fd);
1481 #endif
1482 }
1483 else
1484 do_trunc = 1;
1485
1486 if (option_bool(OPT_EXTRALOG) && src != &forward->frec_src)
1487 {
1488 daemon->log_display_id = src->log_id;
1489 daemon->log_source_addr = &src->source;
1490 log_query(F_UPSTREAM, "query", NULL, "duplicate", 0);
1491 }
1492 }
1493 }
1494
1495 /* The packet is too big for one or more requestors, send them a truncated answer. */
1496 if (do_trunc)
1497 {
1498 size_t hlen, new;
1499 unsigned char *pheader = find_pseudoheader(header, nn, &hlen, NULL, NULL, NULL);
1500
1501 header->ancount = htons(0);
1502 header->nscount = htons(0);
1503 header->arcount = htons(0);
1504 header->hb3 |= HB3_TC;
1505 new = resize_packet(header, nn, pheader, hlen);
1506
1507 daemon->log_display_id = forward->frec_src.log_id;
1508 daemon->log_source_addr = &forward->frec_src.source;
1509 log_query(F_UPSTREAM, NULL, NULL, "truncated", 0);
1510
1511 /* This gets the name back to the state it was in when we started. */
1512 flip_queryname(header, new, prev, &forward->frec_src);
1513
1514 for (src = &forward->frec_src, prev = NULL; src; prev = src, src = src->next)
1515 {
1516 /* If you didn't undertand this above, you won't understand it here either. */
1517 if (prev)
1518 flip_queryname(header, new, prev, src);
1519
1520 if (src->fd != -1 && nn > src->udp_pkt_size)
1521 {
1522 header->id = htons(src->orig_id);
1523 send_from(src->fd, option_bool(OPT_NOWILD) || option_bool (OPT_CLEVERBIND), daemon->packet, new,
1524 &src->source, &src->dest, src->iface);
1525
1526 #ifdef HAVE_DUMPFILE
1527 dump_packet_udp(DUMP_REPLY, daemon->packet, (size_t)new, NULL, &src->source, src->fd);
1528 #endif
1529 }
1530 }
1531 }
1532 }
1533
1534 free_frec(forward); /* cancel */
1535 }
1536
1537
1538 #ifdef HAVE_CONNTRACK
1539 static int is_query_allowed_for_mark(u32 mark, const char *name)
1540 {
1541 int is_allowable_name, did_validate_name = 0;
1542 struct allowlist *allowlists;
1543 char **patterns_pos;
1544
1545 for (allowlists = daemon->allowlists; allowlists; allowlists = allowlists->next)
1546 if (allowlists->mark == (mark & daemon->allowlist_mask & allowlists->mask))
1547 for (patterns_pos = allowlists->patterns; *patterns_pos; patterns_pos++)
1548 {
1549 if (!strcmp(*patterns_pos, "*"))
1550 return 1;
1551 if (!did_validate_name)
1552 {
1553 is_allowable_name = name ? is_valid_dns_name(name) : 0;
1554 did_validate_name = 1;
1555 }
1556 if (is_allowable_name && is_dns_name_matching_pattern(name, *patterns_pos))
1557 return 1;
1558 }
1559 return 0;
1560 }
1561
1562 static size_t answer_disallowed(struct dns_header *header, size_t qlen, u32 mark, const char *name)
1563 {
1564 unsigned char *p;
1565 (void)name;
1566 (void)mark;
1567
1568 #ifdef HAVE_UBUS
1569 if (name)
1570 ubus_event_bcast_connmark_allowlist_refused(mark, name);
1571 #endif
1572
1573 setup_reply(header, /* flags: */ 0, EDE_BLOCKED);
1574
1575 if (!(p = skip_questions(header, qlen)))
1576 return 0;
1577 return p - (unsigned char *)header;
1578 }
1579 #endif
1580
1581 void receive_query(struct listener *listen, time_t now)
1582 {
1583 struct dns_header *header = (struct dns_header *)daemon->packet;
1584 union mysockaddr source_addr;
1585 unsigned char *pheader;
1586 unsigned short type, udp_size = PACKETSZ; /* default if no EDNS0 */
1587 union all_addr dst_addr;
1588 struct in_addr netmask, dst_addr_4;
1589 size_t m;
1590 ssize_t n;
1591 int if_index = 0, auth_dns = 0, do_bit = 0;
1592 unsigned int fwd_flags = 0;
1593 int stale = 0, filtered = 0, ede = EDE_UNSET, do_forward = 0;
1594 int metric, fd;
1595 struct blockdata *saved_question = NULL;
1596 #ifdef HAVE_CONNTRACK
1597 unsigned int mark = 0;
1598 int have_mark = 0;
1599 int allowed = 1;
1600 # ifdef HAVE_UBUS
1601 int report = 0;
1602 # endif
1603 #endif
1604 #ifdef HAVE_AUTH
1605 int local_auth = 0;
1606 #endif
1607 struct iovec iov[1];
1608 struct msghdr msg;
1609 struct cmsghdr *cmptr;
1610 union {
1611 struct cmsghdr align; /* this ensures alignment */
1612 char control6[CMSG_SPACE(sizeof(struct in6_pktinfo))];
1613 #if defined(HAVE_LINUX_NETWORK)
1614 char control[CMSG_SPACE(sizeof(struct in_pktinfo))];
1615 #elif defined(IP_RECVDSTADDR) && defined(HAVE_SOLARIS_NETWORK)
1616 char control[CMSG_SPACE(sizeof(struct in_addr)) +
1617 CMSG_SPACE(sizeof(unsigned int))];
1618 #elif defined(IP_RECVDSTADDR)
1619 char control[CMSG_SPACE(sizeof(struct in_addr)) +
1620 CMSG_SPACE(sizeof(struct sockaddr_dl))];
1621 #endif
1622 } control_u;
1623 int family = listen->addr.sa.sa_family;
1624 /* Can always get recvd interface for IPv6 */
1625 int check_dst = !option_bool(OPT_NOWILD) || family == AF_INET6;
1626
1627 /* packet buffer overwritten */
1628 daemon->srv_save = NULL;
1629
1630 dst_addr_4.s_addr = dst_addr.addr4.s_addr = 0;
1631 netmask.s_addr = 0;
1632
1633 if (option_bool(OPT_NOWILD) && listen->iface)
1634 {
1635 auth_dns = listen->iface->dns_auth;
1636
1637 if (family == AF_INET)
1638 {
1639 dst_addr_4 = dst_addr.addr4 = listen->iface->addr.in.sin_addr;
1640 netmask = listen->iface->netmask;
1641 }
1642 }
1643
1644 iov[0].iov_base = daemon->packet;
1645 iov[0].iov_len = daemon->edns_pktsz;
1646
1647 msg.msg_control = control_u.control;
1648 msg.msg_controllen = sizeof(control_u);
1649 msg.msg_flags = 0;
1650 msg.msg_name = &source_addr;
1651 msg.msg_namelen = sizeof(source_addr);
1652 msg.msg_iov = iov;
1653 msg.msg_iovlen = 1;
1654
1655 if ((n = recvmsg(listen->fd, &msg, 0)) == -1)
1656 return;
1657
1658 if (n < (int)sizeof(struct dns_header) ||
1659 (msg.msg_flags & MSG_TRUNC) ||
1660 (header->hb3 & HB3_QR))
1661 return;
1662
1663 /* Clear buffer beyond request to avoid risk of
1664 information disclosure. */
1665 memset(daemon->packet + n, 0, daemon->edns_pktsz - n);
1666
1667 source_addr.sa.sa_family = family;
1668
1669 if (family == AF_INET)
1670 {
1671 /* Source-port == 0 is an error, we can't send back to that.
1672 http://www.ietf.org/mail-archive/web/dnsop/current/msg11441.html */
1673 if (source_addr.in.sin_port == 0)
1674 return;
1675 }
1676 else
1677 {
1678 /* Source-port == 0 is an error, we can't send back to that. */
1679 if (source_addr.in6.sin6_port == 0)
1680 return;
1681 source_addr.in6.sin6_flowinfo = 0;
1682 }
1683
1684 /* We can be configured to only accept queries from at-most-one-hop-away addresses. */
1685 if (option_bool(OPT_LOCAL_SERVICE))
1686 {
1687 struct addrlist *addr;
1688
1689 if (family == AF_INET6)
1690 {
1691 for (addr = daemon->interface_addrs; addr; addr = addr->next)
1692 if ((addr->flags & ADDRLIST_IPV6) &&
1693 is_same_net6(&addr->addr.addr6, &source_addr.in6.sin6_addr, addr->prefixlen))
1694 break;
1695 }
1696 else
1697 {
1698 struct in_addr netmask;
1699 for (addr = daemon->interface_addrs; addr; addr = addr->next)
1700 {
1701 netmask.s_addr = htonl(~(in_addr_t)0 << (32 - addr->prefixlen));
1702 if (!(addr->flags & ADDRLIST_IPV6) &&
1703 is_same_net(addr->addr.addr4, source_addr.in.sin_addr, netmask))
1704 break;
1705 }
1706 }
1707 if (!addr)
1708 {
1709 static int warned = 0;
1710 if (!warned)
1711 {
1712 prettyprint_addr(&source_addr, daemon->addrbuff);
1713 my_syslog(LOG_WARNING, _("ignoring query from non-local network %s (logged only once)"), daemon->addrbuff);
1714 warned = 1;
1715 }
1716 return;
1717 }
1718 }
1719
1720 if (check_dst)
1721 {
1722 struct ifreq ifr;
1723
1724 if (msg.msg_controllen < sizeof(struct cmsghdr))
1725 return;
1726
1727 #if defined(HAVE_LINUX_NETWORK)
1728 if (family == AF_INET)
1729 for (cmptr = CMSG_FIRSTHDR(&msg); cmptr; cmptr = CMSG_NXTHDR(&msg, cmptr))
1730 if (cmptr->cmsg_level == IPPROTO_IP && cmptr->cmsg_type == IP_PKTINFO)
1731 {
1732 union {
1733 unsigned char *c;
1734 struct in_pktinfo *p;
1735 } p;
1736 p.c = CMSG_DATA(cmptr);
1737 dst_addr_4 = dst_addr.addr4 = p.p->ipi_spec_dst;
1738 if_index = p.p->ipi_ifindex;
1739 }
1740 #elif defined(IP_RECVDSTADDR) && defined(IP_RECVIF)
1741 if (family == AF_INET)
1742 {
1743 for (cmptr = CMSG_FIRSTHDR(&msg); cmptr; cmptr = CMSG_NXTHDR(&msg, cmptr))
1744 {
1745 union {
1746 unsigned char *c;
1747 unsigned int *i;
1748 struct in_addr *a;
1749 #ifndef HAVE_SOLARIS_NETWORK
1750 struct sockaddr_dl *s;
1751 #endif
1752 } p;
1753 p.c = CMSG_DATA(cmptr);
1754 if (cmptr->cmsg_level == IPPROTO_IP && cmptr->cmsg_type == IP_RECVDSTADDR)
1755 dst_addr_4 = dst_addr.addr4 = *(p.a);
1756 else if (cmptr->cmsg_level == IPPROTO_IP && cmptr->cmsg_type == IP_RECVIF)
1757 #ifdef HAVE_SOLARIS_NETWORK
1758 if_index = *(p.i);
1759 #else
1760 if_index = p.s->sdl_index;
1761 #endif
1762 }
1763 }
1764 #endif
1765
1766 if (family == AF_INET6)
1767 {
1768 for (cmptr = CMSG_FIRSTHDR(&msg); cmptr; cmptr = CMSG_NXTHDR(&msg, cmptr))
1769 if (cmptr->cmsg_level == IPPROTO_IPV6 && cmptr->cmsg_type == daemon->v6pktinfo)
1770 {
1771 union {
1772 unsigned char *c;
1773 struct in6_pktinfo *p;
1774 } p;
1775 p.c = CMSG_DATA(cmptr);
1776
1777 dst_addr.addr6 = p.p->ipi6_addr;
1778 if_index = p.p->ipi6_ifindex;
1779 }
1780 }
1781
1782 /* enforce available interface configuration */
1783
1784 if (!indextoname(listen->fd, if_index, ifr.ifr_name))
1785 return;
1786
1787 if (!iface_check(family, &dst_addr, ifr.ifr_name, &auth_dns))
1788 {
1789 if (!option_bool(OPT_CLEVERBIND))
1790 enumerate_interfaces(0);
1791 if (!loopback_exception(listen->fd, family, &dst_addr, ifr.ifr_name) &&
1792 !label_exception(if_index, family, &dst_addr))
1793 return;
1794 }
1795
1796 if (family == AF_INET && option_bool(OPT_LOCALISE))
1797 {
1798 struct irec *iface;
1799
1800 /* get the netmask of the interface which has the address we were sent to.
1801 This is no necessarily the interface we arrived on. */
1802
1803 for (iface = daemon->interfaces; iface; iface = iface->next)
1804 if (iface->addr.sa.sa_family == AF_INET &&
1805 iface->addr.in.sin_addr.s_addr == dst_addr_4.s_addr)
1806 break;
1807
1808 /* interface may be new */
1809 if (!iface && !option_bool(OPT_CLEVERBIND))
1810 enumerate_interfaces(0);
1811
1812 for (iface = daemon->interfaces; iface; iface = iface->next)
1813 if (iface->addr.sa.sa_family == AF_INET &&
1814 iface->addr.in.sin_addr.s_addr == dst_addr_4.s_addr)
1815 break;
1816
1817 /* If we failed, abandon localisation */
1818 if (iface)
1819 netmask = iface->netmask;
1820 else
1821 dst_addr_4.s_addr = 0;
1822 }
1823 }
1824
1825 /* log_query gets called indirectly all over the place, so
1826 pass these in global variables - sorry. */
1827 daemon->log_display_id = ++daemon->log_id;
1828 daemon->log_source_addr = &source_addr;
1829
1830 #ifdef HAVE_DUMPFILE
1831 dump_packet_udp(DUMP_QUERY, daemon->packet, (size_t)n, &source_addr, NULL, listen->fd);
1832 #endif
1833
1834 #ifdef HAVE_CONNTRACK
1835 if (option_bool(OPT_CMARK_ALST_EN))
1836 have_mark = get_incoming_mark(&source_addr, &dst_addr, /* istcp: */ 0, &mark);
1837 #endif
1838
1839 if (OPCODE(header) != QUERY)
1840 log_query_mysockaddr((auth_dns ? F_NOERR : 0) | F_QUERY | F_FORWARD | F_CONFIG, NULL, &source_addr, NULL, OPCODE(header));
1841 else if (extract_request(header, (size_t)n, daemon->namebuff, &type, NULL))
1842 {
1843 #ifdef HAVE_AUTH
1844 struct auth_zone *zone;
1845 #endif
1846 log_query_mysockaddr((auth_dns ? F_NOERR | F_AUTH : 0 ) | F_QUERY | F_FORWARD, daemon->namebuff,
1847 &source_addr, NULL, type);
1848
1849 #ifdef HAVE_AUTH
1850 /* Find queries for zones we're authoritative for, and answer them directly.
1851 The exception to this is DS queries for the zone route. They
1852 have to come from the parent zone. Since dnsmasq's auth server
1853 can't do DNSSEC, the zone will be unsigned, and anything using
1854 dnsmasq as a forwarder and doing validation will be expecting to
1855 see the proof of non-existence from the parent. */
1856 if (!auth_dns && !option_bool(OPT_LOCALISE))
1857 for (zone = daemon->auth_zones; zone; zone = zone->next)
1858 {
1859 char *cut;
1860
1861 if (in_zone(zone, daemon->namebuff, &cut))
1862 {
1863 if (type != T_DS || cut)
1864 {
1865 auth_dns = 1;
1866 local_auth = 1;
1867 }
1868 break;
1869 }
1870 }
1871 #endif
1872
1873 #ifdef HAVE_LOOP
1874 /* Check for forwarding loop */
1875 if (detect_loop(daemon->namebuff, type))
1876 return;
1877 #endif
1878 }
1879
1880 if (find_pseudoheader(header, (size_t)n, NULL, &pheader, NULL, NULL))
1881 {
1882 unsigned short flags;
1883
1884 fwd_flags |= FREC_HAS_PHEADER;
1885
1886 GETSHORT(udp_size, pheader);
1887 pheader += 2; /* ext_rcode */
1888 GETSHORT(flags, pheader);
1889
1890 if (flags & 0x8000)
1891 do_bit = 1;/* do bit */
1892
1893 /* If the client provides an EDNS0 UDP size, use that to limit our reply.
1894 (bounded by the maximum configured). If no EDNS0, then it
1895 defaults to 512. We write this value into the query packet too, so that
1896 if it's forwarded, we don't specify a maximum size greater than we can handle. */
1897 if (udp_size > daemon->edns_pktsz)
1898 udp_size = daemon->edns_pktsz;
1899 else if (udp_size < PACKETSZ)
1900 udp_size = PACKETSZ; /* Sanity check - can't reduce below default. RFC 6891 6.2.3 */
1901 }
1902
1903 /* RFC 6840 5.7 */
1904 if (do_bit || (header->hb4 & HB4_AD))
1905 fwd_flags |= FREC_AD_QUESTION;
1906
1907 if (do_bit)
1908 fwd_flags |= FREC_DO_QUESTION;
1909
1910 if (header->hb4 & HB4_CD)
1911 fwd_flags |= FREC_CHECKING_DISABLED;
1912
1913 fd = listen->fd;
1914
1915 #ifdef HAVE_CONNTRACK
1916 #ifdef HAVE_AUTH
1917 if (!auth_dns || local_auth)
1918 #endif
1919 if (option_bool(OPT_CMARK_ALST_EN) && have_mark && ((u32)mark & daemon->allowlist_mask))
1920 allowed = is_query_allowed_for_mark((u32)mark, daemon->namebuff);
1921 #endif
1922
1923 if (0);
1924 #ifdef HAVE_CONNTRACK
1925 else if (!allowed)
1926 {
1927 ede = EDE_BLOCKED;
1928 m = answer_disallowed(header, (size_t)n, (u32)mark, daemon->namebuff);
1929 metric = METRIC_DNS_LOCAL_ANSWERED;
1930 }
1931 #endif
1932 #ifdef HAVE_AUTH
1933 else if (auth_dns)
1934 {
1935 m = answer_auth(header, ((char *) header) + udp_size, (size_t)n, now, &source_addr, local_auth);
1936 metric = METRIC_DNS_AUTH_ANSWERED;
1937
1938 #if defined(HAVE_CONNTRACK) && defined(HAVE_UBUS)
1939 if (local_auth)
1940 report = 1;
1941 #endif
1942 }
1943 #endif
1944 else
1945 {
1946 int cacheable;
1947
1948 n = add_edns0_config(header, n, daemon->edns_pktsz, &source_addr, now, &cacheable);
1949 saved_question = blockdata_alloc((char *) header, (size_t)n);
1950
1951 if (!cacheable)
1952 fwd_flags |= FREC_NO_CACHE;
1953
1954 m = answer_request(header, ((char *) header) + udp_size, (size_t)n,
1955 dst_addr_4, netmask, now, fwd_flags & FREC_AD_QUESTION, do_bit, !cacheable, &stale, &filtered);
1956
1957 metric = stale ? METRIC_DNS_STALE_ANSWERED : METRIC_DNS_LOCAL_ANSWERED;
1958
1959 if (m == 0)
1960 do_forward = 1;
1961 else
1962 {
1963 #if defined(HAVE_CONNTRACK) && defined(HAVE_UBUS)
1964 report = 1;
1965 #endif
1966
1967 if (filtered)
1968 ede = EDE_FILTERED;
1969 else if (stale)
1970 ede = EDE_STALE;
1971 }
1972 }
1973
1974 if (m != 0)
1975 {
1976 if (fwd_flags & FREC_HAS_PHEADER)
1977 {
1978 if (ede != EDE_UNSET)
1979 {
1980 u16 swap = htons(ede);
1981
1982 m = add_pseudoheader(header, m, daemon->edns_pktsz, EDNS0_OPTION_EDE,
1983 (unsigned char *)&swap, 2, do_bit, 0);
1984 }
1985 else
1986 m = add_pseudoheader(header, m, daemon->edns_pktsz, 0,
1987 NULL, 0, do_bit, 0);
1988 }
1989
1990 #ifdef HAVE_DUMPFILE
1991 dump_packet_udp(DUMP_REPLY, daemon->packet, m, NULL, &source_addr, listen->fd);
1992 #endif
1993
1994 #if defined(HAVE_CONNTRACK) && defined(HAVE_UBUS)
1995 if (report)
1996 report_addresses(header, m, mark);
1997 #endif
1998
1999 send_from(listen->fd, option_bool(OPT_NOWILD) || option_bool(OPT_CLEVERBIND),
2000 (char *)header, m, &source_addr, &dst_addr, if_index);
2001
2002 daemon->metrics[metric]++;
2003
2004 if (stale)
2005 {
2006 /* We answered with stale cache data, so forward the query anyway to
2007 refresh that. */
2008 do_forward = 1;
2009
2010 /* Don't mark the query with the source in this case. */
2011 daemon->log_source_addr = NULL;
2012
2013 /* We've already answered the client, so don't send it the answer
2014 when it comes back. */
2015 fd = -1;
2016 }
2017 }
2018
2019 if (do_forward && saved_question)
2020 {
2021 /* Get the question back, since it may have been mangled by answer_request() */
2022 blockdata_retrieve(saved_question, (size_t)n, (void *)header);
2023 blockdata_free(saved_question);
2024 saved_question = NULL;
2025
2026 forward_query(fd, &source_addr, &dst_addr, if_index, header, (size_t)n,
2027 udp_size, now, NULL, fwd_flags, 0);
2028 }
2029
2030 blockdata_free(saved_question);
2031 }
2032
2033
2034 /* Send query in header, qsize to a server determined by first,last,start and
2035 get the reply into the buffer passed by outbuff. Return reply size. */
2036 static ssize_t tcp_talk(int first, int last, int start, struct dns_header *header, size_t qsize,
2037 struct iovec *recvbuff, int have_mark, unsigned int mark, struct server **servp)
2038 {
2039 int firstsendto = -1;
2040 u16 length;
2041 unsigned int rsize = 0;
2042 int class, rclass, type, rtype;
2043 unsigned char *p;
2044 struct timeval tv;
2045 struct iovec sendio[2];
2046 #ifdef MSG_FASTOPEN
2047 struct msghdr msg;
2048 #endif
2049
2050 (void)mark;
2051 (void)have_mark;
2052
2053 /* Save the query to make sure we get the answer we expect. */
2054 p = (unsigned char *)(header+1);
2055 if (!extract_name(header, qsize, &p, daemon->namebuff, EXTR_NAME_EXTRACT, 4))
2056 return 0;
2057 GETSHORT(type, p);
2058 GETSHORT(class, p);
2059
2060 length = htons(qsize);
2061 sendio[0].iov_base = &length;
2062 sendio[0].iov_len = sizeof(length);
2063 sendio[1].iov_base = header;
2064 sendio[1].iov_len = qsize;
2065
2066 while (1)
2067 {
2068 int data_sent = 0, fatal = 0;
2069 struct server *serv;
2070
2071 if (firstsendto == -1)
2072 firstsendto = start;
2073 else
2074 {
2075 start++;
2076
2077 if (start == last)
2078 start = first;
2079
2080 if (start == firstsendto)
2081 break;
2082 }
2083
2084 *servp = serv = daemon->serverarray[start];
2085
2086 retry:
2087 if (serv->tcpfd == -1)
2088 {
2089 if ((serv->tcpfd = socket(serv->addr.sa.sa_family, SOCK_STREAM, 0)) == -1)
2090 continue;
2091
2092 #ifdef HAVE_CONNTRACK
2093 /* Copy connection mark of incoming query to outgoing connection. */
2094 if (have_mark)
2095 setsockopt(serv->tcpfd, SOL_SOCKET, SO_MARK, &mark, sizeof(unsigned int));
2096 #endif
2097
2098 if ((!local_bind(serv->tcpfd, &serv->source_addr, serv->interface, 0, 1)))
2099 {
2100 close(serv->tcpfd);
2101 serv->tcpfd = -1;
2102 continue;
2103 }
2104
2105 #if defined(SO_SNDTIMEO) && defined(SO_RCVTIMEO)
2106 /* TCP connections by default take ages to time out.
2107 Set shorter timeouts more appropriate for a DNS server.
2108 We set the recieve timeout as twice the send timeout; we
2109 want to fail quickly on a non-responsive server, but give it time to get an
2110 answer. */
2111 tv.tv_sec = TCP_TIMEOUT;
2112 tv.tv_usec = 0;
2113 setsockopt(serv->tcpfd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
2114 tv.tv_sec += TCP_TIMEOUT;
2115 setsockopt(serv->tcpfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
2116 #endif
2117 #ifdef MSG_FASTOPEN
2118 msg.msg_name = &serv->addr.sa;
2119 msg.msg_namelen = sa_len(&serv->addr);
2120 msg.msg_iov = sendio;
2121 msg.msg_iovlen = 2;
2122 msg.msg_control = NULL;
2123 msg.msg_controllen = 0;
2124 msg.msg_flags = 0;
2125
2126 while (retry_send(sendmsg(serv->tcpfd, &msg, MSG_FASTOPEN)));
2127
2128 if (errno == 0)
2129 data_sent = 1;
2130 else if (errno == ETIMEDOUT || errno == EHOSTUNREACH || errno == EINPROGRESS || errno == ECONNREFUSED)
2131 fatal = 1;
2132 #endif
2133
2134 /* If fastopen failed due to lack of reply, then there's no point in
2135 trying again in non-FASTOPEN mode. */
2136 if (fatal || (!data_sent && connect(serv->tcpfd, &serv->addr.sa, sa_len(&serv->addr)) == -1))
2137 {
2138 int port;
2139
2140 failed:
2141 port = prettyprint_addr(&serv->addr, daemon->addrbuff);
2142 my_syslog(LOG_DEBUG|MS_DEBUG, _("TCP connection failed to %s#%d"), daemon->addrbuff, port);
2143
2144 close(serv->tcpfd);
2145 serv->tcpfd = -1;
2146 continue;
2147 }
2148
2149 daemon->serverarray[first]->last_server = start;
2150 serv->flags &= ~SERV_GOT_TCP;
2151 }
2152
2153 /* We use the _ONCE variant of read_write() here because we've set a timeout on the tcp socket
2154 and wish to abort if the whole data is not read/written within the timeout. */
2155 if ((!data_sent && !read_writev(serv->tcpfd, sendio, 2, RW_WRITE_ONCE)) ||
2156 !read_write(serv->tcpfd, (unsigned char *)&length, sizeof(length), RW_READ_ONCE) ||
2157 !expand_buf(recvbuff, (rsize = ntohs(length))) ||
2158 !read_write(serv->tcpfd, recvbuff->iov_base, rsize, RW_READ_ONCE))
2159 {
2160 /* We get data then EOF, reopen connection to same server,
2161 else try next. This avoids DoS from a server which accepts
2162 connections and then closes them. */
2163 if (serv->flags & SERV_GOT_TCP)
2164 {
2165 close(serv->tcpfd);
2166 serv->tcpfd = -1;
2167 goto retry;
2168 }
2169 else
2170 goto failed;
2171 }
2172 else
2173 {
2174 /* If the question section of the reply doesn't match the question we sent, then
2175 someone might be attempting to insert bogus values into the cache by
2176 sending replies containing questions and bogus answers.
2177 Try another server, or give up */
2178 struct dns_header *header = (struct dns_header *)recvbuff->iov_base;
2179 p = (unsigned char *)(header+1);
2180 if (rsize < (unsigned int)sizeof(struct dns_header) || !(header->hb3 & HB3_QR) || ntohs(header->qdcount) != 1 ||
2181 extract_name(header, rsize, &p, daemon->namebuff, EXTR_NAME_COMPARE, 4) != 1)
2182 continue;
2183
2184 GETSHORT(rtype, p);
2185 GETSHORT(rclass, p);
2186
2187 if (type != rtype || class != rclass)
2188 continue;
2189 }
2190
2191 serv->flags |= SERV_GOT_TCP;
2192
2193 *servp = serv;
2194 return rsize;
2195 }
2196
2197 return 0;
2198 }
2199
2200 #ifdef HAVE_DNSSEC
2201 /* An answer to an downstream query or DNSSEC subquery has
2202 returned truncated. (Which type held in status).
2203 Resend the query (in header) via TCP */
2204 int tcp_from_udp(time_t now, int status, struct dns_header *header, ssize_t *plenp,
2205 int class, char *name, struct server *server,
2206 int *keycount, int *validatecount)
2207 {
2208 int start, first, last, new_status;
2209 ssize_t n = *plenp;
2210 int log_save = daemon->log_display_id;
2211 struct iovec recvbuff;
2212
2213 recvbuff.iov_len = 0;
2214 recvbuff.iov_base = NULL;
2215
2216 *plenp = 0;
2217
2218 /* Set TCP flag in logs. */
2219 daemon->log_display_id = -daemon->log_display_id;
2220
2221 /* send orginal query to same server that generated truncated reply on UDP. */
2222 first = start = server->arrayposn;
2223 last = first + 1;
2224
2225 if (!STAT_ISEQUAL(status, STAT_OK) && (start = dnssec_server(server, name, STAT_ISEQUAL(status, STAT_NEED_DS), &first, &last)) == -1)
2226 new_status = STAT_ABANDONED;
2227 else
2228 {
2229 if (STAT_ISEQUAL(status, STAT_OK))
2230 log_query_mysockaddr(F_SERVER | F_FORWARD, name, &server->addr, NULL, 0);
2231 else
2232 log_query_mysockaddr(F_NOEXTRA | F_DNSSEC | F_SERVER, name, &server->addr,
2233 STAT_ISEQUAL(status, STAT_NEED_KEY) ? "dnssec-query[DNSKEY]" : "dnssec-query[DS]", 0);
2234
2235 if ((n = tcp_talk(first, last, start, header, n, &recvbuff, 0, 0, &server)) == 0)
2236 new_status = STAT_ABANDONED;
2237 else
2238 {
2239 struct dns_header *new_header = (struct dns_header *)recvbuff.iov_base;
2240 new_status = tcp_key_recurse(now, status, new_header, n, class, daemon->namebuff, daemon->keyname, server, 0, 0, keycount, validatecount);
2241
2242 if (STAT_ISEQUAL(status, STAT_OK))
2243 {
2244 /* downstream query: strip DNSSSEC RRs and see if it will
2245 fit in a UDP reply. */
2246 rrfilter(new_header, (size_t *)&n, RRFILTER_DNSSEC);
2247
2248 if (n >= daemon->edns_pktsz)
2249 {
2250 /* still too big, strip optional sections and try again. */
2251 new_header->nscount = htons(0);
2252 new_header->arcount = htons(0);
2253 n = resize_packet(new_header, n, NULL, 0);
2254 if (n >= daemon->edns_pktsz)
2255 {
2256 /* truncating the packet will break the answers, so remove them too
2257 and mark the reply as truncated. */
2258 new_header->ancount = htons(0);
2259 n = resize_packet(new_header, n, NULL, 0);
2260 new_status = STAT_TRUNCATED;
2261 }
2262 }
2263
2264 /* we have succeeded and are no longer blocked talking
2265 on a TCP connection, so if the watchdog alarm goes off,
2266 ignore it. */
2267 daemon->forward_to_tcp = NULL;
2268 /* return the stripped or truncated reply. */
2269 memcpy(header, new_header, n);
2270 *plenp = n;
2271 }
2272 }
2273 }
2274
2275 daemon->log_display_id = log_save;
2276 free(recvbuff.iov_base);
2277 return new_status;
2278 }
2279
2280 /* Recurse down the key hierarchy */
2281 static int tcp_key_recurse(time_t now, int status, struct dns_header *header, size_t n,
2282 int class, char *name, char *keyname, struct server *server,
2283 int have_mark, unsigned int mark, int *keycount, int *validatecount)
2284 {
2285 int first, last, start, new_status;
2286 struct iovec new_packet;
2287 struct dns_header *query_header = NULL, *new_header;
2288
2289 new_packet.iov_base = NULL;
2290 new_packet.iov_len = 0;
2291
2292 while (1)
2293 {
2294 size_t m;
2295 int log_save;
2296
2297 /* limit the amount of work we do, to avoid cycling forever on loops in the DNS */
2298 if (STAT_ISEQUAL(status, STAT_NEED_KEY))
2299 new_status = dnssec_validate_by_ds(now, header, n, name, keyname, class, validatecount);
2300 else if (STAT_ISEQUAL(status, STAT_NEED_DS))
2301 new_status = dnssec_validate_ds(now, header, n, name, keyname, class, validatecount);
2302 else
2303 new_status = dnssec_validate_reply(now, header, n, name, keyname, &class,
2304 !option_bool(OPT_DNSSEC_IGN_NS), NULL, NULL, NULL, NULL, validatecount);
2305
2306 if (!STAT_ISEQUAL(new_status, STAT_NEED_DS) && !STAT_ISEQUAL(new_status, STAT_NEED_KEY) && !STAT_ISEQUAL(new_status, STAT_ABANDONED))
2307 break;
2308
2309 if ((*keycount)-- == 0)
2310 {
2311 my_syslog(LOG_WARNING, _("limit exceeded: per-query subqueries"));
2312 new_status = STAT_ABANDONED;
2313 }
2314
2315 if (STAT_ISEQUAL(new_status, STAT_ABANDONED))
2316 {
2317 /* Log the actual validation that made us barf. */
2318 if (extract_name(header, n, NULL, daemon->namebuff, EXTR_NAME_EXTRACT, 0))
2319 my_syslog(LOG_WARNING, _("validation of %s failed: resource limit exceeded."),
2320 daemon->namebuff[0] ? daemon->namebuff : ".");
2321 break;
2322 }
2323
2324 /* Can't validate because we need a key/DS whose name now in keyname.
2325 Make query for same in UDP packet buffer, recurse to validate*/
2326 query_header = (struct dns_header *)daemon->packet;
2327 daemon->srv_save = NULL;
2328
2329 m = dnssec_generate_query(query_header, daemon->edns_pktsz, keyname, class, 0,
2330 STAT_ISEQUAL(new_status, STAT_NEED_KEY) ? T_DNSKEY : T_DS);
2331
2332 if ((start = dnssec_server(server, keyname, STAT_ISEQUAL(new_status, STAT_NEED_DS), &first, &last)) == -1 ||
2333 (m = tcp_talk(first, last, start, query_header, m, &new_packet, have_mark, mark, &server)) == 0)
2334 {
2335 new_status = STAT_ABANDONED;
2336 break;
2337 }
2338
2339 new_header = new_packet.iov_base;
2340 log_save = daemon->log_display_id;
2341 daemon->log_display_id = -(++daemon->log_id);
2342
2343 log_query_mysockaddr(F_NOEXTRA | F_DNSSEC | F_SERVER, keyname, &server->addr,
2344 STAT_ISEQUAL(new_status, STAT_NEED_KEY) ? "dnssec-query[DNSKEY]" : "dnssec-query[DS]", 0);
2345
2346 new_status = tcp_key_recurse(now, new_status, new_header, m, class, name, keyname, server,
2347 have_mark, mark, keycount, validatecount);
2348
2349 daemon->log_display_id = log_save;
2350
2351 /* If we got STAT_OK from a DS or KEY validation on recursing, loop round and try the failed validation again. */
2352 if (!STAT_ISEQUAL(new_status, STAT_OK))
2353 break;
2354 }
2355
2356 free(new_packet.iov_base);
2357
2358 return new_status;
2359 }
2360 #endif
2361
2362
2363 /* The daemon forks before calling this: it should deal with one connection,
2364 blocking as necessary, and then return. Note, need to be a bit careful
2365 about resources for debug mode, when the fork is suppressed: that's
2366 done by the caller, which also frees bigbuff. */
2367 void tcp_request(int confd, time_t now, struct iovec *bigbuff,
2368 union mysockaddr *local_addr, struct in_addr netmask, int auth_dns)
2369 {
2370 size_t size = 0;
2371 int norebind = 0;
2372 #ifdef HAVE_CONNTRACK
2373 int allowed = 1;
2374 #endif
2375 #ifdef HAVE_AUTH
2376 int local_auth = 0;
2377 #endif
2378 int checking_disabled, do_bit = 0, ad_reqd = 0, have_pseudoheader = 0;
2379 unsigned short qtype;
2380 unsigned int gotname = 0;
2381 u16 tcp_len, out_len;
2382 struct dns_header *header, *out_header;
2383 struct server *serv;
2384 struct in_addr dst_addr_4;
2385 union mysockaddr peer_addr;
2386 socklen_t peer_len = sizeof(union mysockaddr);
2387 int query_count = 0;
2388 unsigned char *pheader;
2389 unsigned int mark = 0;
2390 int have_mark = 0;
2391 int first, last, filtered, do_stale = 0;
2392 struct iovec out_iov[2];
2393
2394 bigbuff->iov_base = NULL;
2395 bigbuff->iov_len = 0;
2396
2397 if (getpeername(confd, (struct sockaddr *)&peer_addr, &peer_len) == -1)
2398 return;
2399
2400 #ifdef HAVE_CONNTRACK
2401 /* Get connection mark of incoming query to set on outgoing connections. */
2402 if (option_bool(OPT_CONNTRACK) || option_bool(OPT_CMARK_ALST_EN))
2403 {
2404 union all_addr local;
2405
2406 if (local_addr->sa.sa_family == AF_INET6)
2407 local.addr6 = local_addr->in6.sin6_addr;
2408 else
2409 local.addr4 = local_addr->in.sin_addr;
2410
2411 have_mark = get_incoming_mark(&peer_addr, &local, 1, &mark);
2412 }
2413 #endif
2414
2415 /* We can be configured to only accept queries from at-most-one-hop-away addresses. */
2416 if (option_bool(OPT_LOCAL_SERVICE))
2417 {
2418 struct addrlist *addr;
2419
2420 if (peer_addr.sa.sa_family == AF_INET6)
2421 {
2422 for (addr = daemon->interface_addrs; addr; addr = addr->next)
2423 if ((addr->flags & ADDRLIST_IPV6) &&
2424 is_same_net6(&addr->addr.addr6, &peer_addr.in6.sin6_addr, addr->prefixlen))
2425 break;
2426 }
2427 else
2428 {
2429 struct in_addr netmask;
2430 for (addr = daemon->interface_addrs; addr; addr = addr->next)
2431 {
2432 netmask.s_addr = htonl(~(in_addr_t)0 << (32 - addr->prefixlen));
2433 if (!(addr->flags & ADDRLIST_IPV6) &&
2434 is_same_net(addr->addr.addr4, peer_addr.in.sin_addr, netmask))
2435 break;
2436 }
2437 }
2438 if (!addr)
2439 {
2440 prettyprint_addr(&peer_addr, daemon->addrbuff);
2441 my_syslog(LOG_WARNING, _("ignoring query from non-local network %s"), daemon->addrbuff);
2442 return;
2443 }
2444 }
2445
2446 while (1)
2447 {
2448 int cacheable = 1, stale = 0, ede = EDE_UNSET;
2449 size_t m = 0;
2450 unsigned int flags = 0;
2451 #ifdef HAVE_AUTH
2452 struct auth_zone *zone;
2453 #endif
2454
2455 if (!do_stale)
2456 {
2457 if (query_count >= TCP_MAX_QUERIES)
2458 break;
2459
2460 /* Now get the query into the normal UDP packet buffer.
2461 Ignore queries longer than this. If we're answering locally,
2462 copy the query into the output buffer, but for forwarding, tcp_talk()
2463 wants the query in different buffer from the reply.
2464 Note that we overwrote any saved UDP query - this only matters in debug mode. */
2465 daemon->srv_save = NULL;
2466 if (!read_write(confd, (unsigned char *)&tcp_len, sizeof(tcp_len), RW_READ) ||
2467 !(size = ntohs(tcp_len)) || size > (size_t)daemon->packet_buff_sz ||
2468 !read_write(confd, (unsigned char *)daemon->packet, size, RW_READ))
2469 break;
2470
2471 /* header == query */
2472 header = (struct dns_header *)daemon->packet;
2473
2474 if (size < (int)sizeof(struct dns_header) || (header->hb3 & HB3_QR))
2475 continue;
2476
2477 /* Make sure we have a buffer big enough for the largest answer. */
2478 expand_buf(bigbuff, 65536 + MAXDNAME + RRFIXEDSZ);
2479 out_header = bigbuff->iov_base;
2480
2481 /* Add edns0 pheader to query */
2482 size = add_edns0_config(header, size, daemon->packet_buff_sz, &peer_addr, now, &cacheable);
2483
2484 /* Clear buffer to avoid risk of information disclosure. */
2485 memset(bigbuff->iov_base, 0, bigbuff->iov_len);
2486 /* Copy query into output buffer for local answering */
2487 memcpy(out_header, header, size);
2488
2489 query_count++;
2490
2491 /* log_query gets called indirectly all over the place, so
2492 pass these in global variables - sorry.
2493 log_display_id is negative for TCP connections. */
2494 daemon->log_display_id = -(++daemon->log_id);
2495 daemon->log_source_addr = &peer_addr;
2496
2497 if (OPCODE(header) != QUERY)
2498 {
2499 log_query_mysockaddr((auth_dns ? F_NOERR : 0) | F_QUERY | F_FORWARD | F_CONFIG, NULL, &peer_addr, NULL, OPCODE(header));
2500 gotname = 0;
2501 flags = F_RCODE;
2502 }
2503 else if (!(gotname = extract_request(header, (unsigned int)size, daemon->namebuff, &qtype, NULL)))
2504 ede = EDE_INVALID_DATA;
2505 else
2506 {
2507 do_bit = 0;
2508
2509 if (find_pseudoheader(header, (size_t)size, NULL, &pheader, NULL, NULL))
2510 {
2511 unsigned short ede_flags;
2512
2513 have_pseudoheader = 1;
2514 pheader += 4; /* udp_size, ext_rcode */
2515 GETSHORT(ede_flags, pheader);
2516
2517 if (ede_flags & 0x8000)
2518 do_bit = 1; /* do bit */
2519 }
2520
2521 log_query_mysockaddr((auth_dns ? F_NOERR | F_AUTH : 0) | F_QUERY | F_FORWARD, daemon->namebuff,
2522 &peer_addr, NULL, qtype);
2523
2524 #ifdef HAVE_AUTH
2525 /* Find queries for zones we're authoritative for, and answer them directly.
2526 The exception to this is DS queries for the zone route. They
2527 have to come from the parent zone. Since dnsmasq's auth server
2528 can't do DNSSEC, the zone will be unsigned, and anything using
2529 dnsmasq as a forwarder and doing validation will be expecting to
2530 see the proof of non-existence from the parent. */
2531 if (!auth_dns && !option_bool(OPT_LOCALISE))
2532 for (zone = daemon->auth_zones; zone; zone = zone->next)
2533 {
2534 char *cut;
2535
2536 if (in_zone(zone, daemon->namebuff, &cut))
2537 {
2538 if (qtype != T_DS || cut)
2539 {
2540 auth_dns = 1;
2541 local_auth = 1;
2542 }
2543 break;
2544 }
2545 }
2546 #endif
2547
2548 norebind = domain_no_rebind(daemon->namebuff);
2549
2550 if (local_addr->sa.sa_family == AF_INET)
2551 dst_addr_4 = local_addr->in.sin_addr;
2552 else
2553 dst_addr_4.s_addr = 0;
2554
2555 ad_reqd = do_bit;
2556 /* RFC 6840 5.7 */
2557 if (header->hb4 & HB4_AD)
2558 ad_reqd = 1;
2559
2560 #ifdef HAVE_CONNTRACK
2561 #ifdef HAVE_AUTH
2562 if (!auth_dns || local_auth)
2563 #endif
2564 if (option_bool(OPT_CMARK_ALST_EN) && have_mark && ((u32)mark & daemon->allowlist_mask))
2565 allowed = is_query_allowed_for_mark((u32)mark, daemon->namebuff);
2566 #endif
2567
2568 if (0);
2569 #ifdef HAVE_CONNTRACK
2570 else if (!allowed)
2571 {
2572 ede = EDE_BLOCKED;
2573 m = answer_disallowed(out_header, size, (u32)mark, daemon->namebuff);
2574 }
2575 #endif
2576 #ifdef HAVE_AUTH
2577 else if (auth_dns)
2578 m = answer_auth(out_header, ((char *) out_header) + 65536, (size_t)size, now, &peer_addr, local_auth);
2579 #endif
2580 else
2581 m = answer_request(out_header, ((char *) out_header) + 65536, (size_t)size,
2582 dst_addr_4, netmask, now, ad_reqd, do_bit, !cacheable, &stale, &filtered);
2583 }
2584 }
2585
2586 /* Do this by steam now we're not in the select() loop */
2587 check_log_writer(1);
2588
2589 if (!flags && m == 0 && ede == EDE_UNSET)
2590 {
2591 struct server *master;
2592 int start;
2593 int no_cache_dnssec = 0, cache_secure = 0, bogusanswer = 0;
2594
2595 /* save state of "cd" flag in query */
2596 checking_disabled = header->hb4 & HB4_CD;
2597
2598 if (lookup_domain(daemon->namebuff, gotname, &first, &last))
2599 flags = is_local_answer(now, first, daemon->namebuff);
2600 else
2601 ede = EDE_NOT_READY;
2602
2603 if (!flags && ede == EDE_UNSET)
2604 {
2605 /* don't forward A or AAAA queries for simple names, except the empty name */
2606 if (option_bool(OPT_NODOTS_LOCAL) &&
2607 (gotname & (F_IPV4 | F_IPV6)) &&
2608 !strchr(daemon->namebuff, '.') &&
2609 strlen(daemon->namebuff) != 0)
2610 flags = check_for_local_domain(daemon->namebuff, now) ? F_NOERR : F_NXDOMAIN;
2611 else
2612 {
2613 master = daemon->serverarray[first];
2614
2615 if (option_bool(OPT_ORDER) || master->last_server == -1)
2616 start = first;
2617 else
2618 start = master->last_server;
2619
2620 #ifdef HAVE_DNSSEC
2621 if (option_bool(OPT_DNSSEC_VALID))
2622 {
2623 size = add_do_bit(header, size, daemon->edns_pktsz);
2624
2625 /* For debugging, set Checking Disabled, otherwise, have the upstream check too,
2626 this allows it to select auth servers when one is returning bad data. */
2627 if (option_bool(OPT_DNSSEC_DEBUG))
2628 header->hb4 |= HB4_CD;
2629 }
2630 #endif
2631
2632 /* Loop round available servers until we succeed in connecting to one. */
2633 if ((m = tcp_talk(first, last, start, header, size, bigbuff, have_mark, mark, &serv)) == 0)
2634 ede = EDE_NETERR;
2635 else
2636 {
2637 /* just in case tcp_talk() expanded buffer - should never happen */
2638 out_header = bigbuff->iov_base;
2639 /* get query name again for logging - may have been overwritten */
2640 if (!extract_name(out_header, (unsigned int)size, NULL, daemon->namebuff, EXTR_NAME_EXTRACT, 0))
2641 strcpy(daemon->namebuff, "query");
2642 log_query_mysockaddr(F_SERVER | F_FORWARD, daemon->namebuff, &serv->addr, NULL, 0);
2643
2644 #ifdef HAVE_DNSSEC
2645 if (option_bool(OPT_DNSSEC_VALID))
2646 {
2647 /* Clear this in case we don't call tcp_key_recurse() below */
2648 memset(daemon->rr_status, 0, sizeof(*daemon->rr_status) * daemon->rr_status_sz);
2649
2650 if (checking_disabled || (header->hb4 & HB4_CD))
2651 no_cache_dnssec = 1;
2652 else
2653 {
2654 int keycount = daemon->limit[LIMIT_WORK]; /* Limit to number of DNSSEC questions, to catch loops and avoid filling cache. */
2655 int validatecount = daemon->limit[LIMIT_CRYPTO];
2656 /* tcp_key_recurse() may overwrite packetbuf, and thuse *header is now invalid */
2657 int status = tcp_key_recurse(now, STAT_OK, out_header, m, 0, daemon->namebuff, daemon->keyname,
2658 serv, have_mark, mark, &keycount, &validatecount);
2659 char *result, *domain = "result";
2660
2661 union all_addr a;
2662 ede = errflags_to_ede(status);
2663
2664 if (STAT_ISEQUAL(status, STAT_ABANDONED))
2665 {
2666 result = "ABANDONED";
2667 status = STAT_BOGUS;
2668 if (ede == EDE_UNSET)
2669 ede = EDE_OTHER;
2670 }
2671 else
2672 result = (STAT_ISEQUAL(status, STAT_SECURE) ? "SECURE" : (STAT_ISEQUAL(status, STAT_INSECURE) ? "INSECURE" : "BOGUS"));
2673
2674 if (STAT_ISEQUAL(status, STAT_SECURE))
2675 cache_secure = 1;
2676 else if (STAT_ISEQUAL(status, STAT_BOGUS))
2677 {
2678 if (ede == EDE_UNSET)
2679 ede = EDE_DNSSEC_BOGUS;
2680 no_cache_dnssec = 1;
2681 bogusanswer = 1;
2682
2683 if (extract_name(out_header, m, NULL, daemon->namebuff, EXTR_NAME_EXTRACT, 0))
2684 domain = daemon->namebuff;
2685 }
2686
2687 a.log.ede = ede;
2688 log_query(F_SECSTAT, domain, &a, result, 0);
2689 if (ede == EDE_US_SERVFAIL)
2690 ede = EDE_DNSSEC_BOGUS;
2691
2692 if ((daemon->limit[LIMIT_CRYPTO] - validatecount) > (int)daemon->metrics[METRIC_CRYPTO_HWM])
2693 daemon->metrics[METRIC_CRYPTO_HWM] = daemon->limit[LIMIT_CRYPTO] - validatecount;
2694
2695 if ((daemon->limit[LIMIT_WORK] - keycount) > (int)daemon->metrics[METRIC_WORK_HWM])
2696 daemon->metrics[METRIC_WORK_HWM] = daemon->limit[LIMIT_WORK] - keycount;
2697
2698 /* include DNSSEC queries in the limit for a connection. */
2699 query_count += daemon->limit[LIMIT_WORK] - keycount;
2700 }
2701 }
2702 #endif
2703
2704
2705 /* restore CD bit to the value in the query */
2706 if (checking_disabled)
2707 out_header->hb4 |= HB4_CD;
2708 else
2709 out_header->hb4 &= ~HB4_CD;
2710
2711 /* Never cache answers which are contingent on the source or MAC address EDSN0 option,
2712 since the cache is ignorant of such things. */
2713 if (!cacheable)
2714 no_cache_dnssec = 1;
2715
2716 m = process_reply(out_header, now, serv, (unsigned int)m,
2717 option_bool(OPT_NO_REBIND) && !norebind, no_cache_dnssec, cache_secure, bogusanswer,
2718 ad_reqd, do_bit, !have_pseudoheader, &peer_addr, 65536, ede);
2719
2720 /* process_reply() adds pheader itself */
2721 have_pseudoheader = 0;
2722 }
2723 }
2724 }
2725 }
2726
2727 if (do_stale)
2728 break;
2729
2730 /* In case of local answer or no connections made. */
2731 if (m == 0)
2732 {
2733 if (!(m = make_local_answer(flags, gotname, size, out_header, daemon->namebuff,
2734 65536, first, last, ede)))
2735 break;
2736 }
2737 else if (ede == EDE_UNSET)
2738 {
2739 if (filtered)
2740 ede = EDE_FILTERED;
2741 else if (stale)
2742 ede = EDE_STALE;
2743 }
2744
2745 if (have_pseudoheader)
2746 {
2747 u16 swap = htons((u16)ede);
2748
2749 if (ede != EDE_UNSET)
2750 m = add_pseudoheader(out_header, m, 65536, EDNS0_OPTION_EDE, (unsigned char *)&swap, 2, do_bit, 0);
2751 else
2752 m = add_pseudoheader(out_header, m, 65536, 0, NULL, 0, do_bit, 0);
2753 }
2754
2755 check_log_writer(1);
2756
2757 #if defined(HAVE_CONNTRACK) && defined(HAVE_UBUS)
2758 #ifdef HAVE_AUTH
2759 if (!auth_dns || local_auth)
2760 #endif
2761 if (option_bool(OPT_CMARK_ALST_EN) && have_mark && ((u32)mark & daemon->allowlist_mask))
2762 report_addresses(header, m, mark);
2763 #endif
2764
2765 /* use scatter-gather IO so that length doesn't end up in separate packet. */
2766 out_len = htons(m);
2767 out_iov[0].iov_len = sizeof(out_len);
2768 out_iov[0].iov_base = &out_len;
2769 out_iov[1].iov_len = m;
2770 out_iov[1].iov_base = bigbuff->iov_base;
2771 if (!read_writev(confd, out_iov, 2, RW_WRITE))
2772 break;
2773
2774 /* If we answered with stale data, this process will now try and get fresh data into
2775 the cache and cannot therefore accept new queries. Close the incoming
2776 connection to signal that to the client. Then set do_stale and loop round
2777 once more to try and get fresh data, after which we exit. */
2778 if (stale)
2779 {
2780 shutdown(confd, SHUT_RDWR);
2781 close(confd);
2782 do_stale = 1;
2783 /* Don't mark the query with the source when refreshing stale data. */
2784 daemon->log_source_addr = NULL;
2785 }
2786 }
2787
2788 /* If we ran once to get fresh data, confd is already closed. */
2789 if (!do_stale)
2790 {
2791 shutdown(confd, SHUT_RDWR);
2792 close(confd);
2793 }
2794
2795 check_log_writer(1);
2796 }
2797
2798 /* return a UDP socket bound to a random port, have to cope with straying into
2799 occupied port nos and reserved ones. */
2800 static int random_sock(struct server *s)
2801 {
2802 int fd;
2803
2804 if ((fd = socket(s->source_addr.sa.sa_family, SOCK_DGRAM, 0)) != -1)
2805 {
2806 /* We need to set IPV6ONLY so we can use the same ports
2807 for IPv4 and IPV6, otherwise, in restriced port situations,
2808 we can end up with all our available ports in use for
2809 one address family, and the other address family cannot be used. */
2810 if (s->source_addr.sa.sa_family == AF_INET6)
2811 {
2812 int opt = 1;
2813
2814 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &opt, sizeof(opt)) == -1)
2815 {
2816 close(fd);
2817 return -1;
2818 }
2819 }
2820
2821 if (local_bind(fd, &s->source_addr, s->interface, s->ifindex, 0))
2822 return fd;
2823
2824 /* don't log errors due to running out of available ports, we handle those. */
2825 if (!sockaddr_isnull(&s->source_addr) || errno != EADDRINUSE)
2826 {
2827 if (s->interface[0] == 0)
2828 (void)prettyprint_addr(&s->source_addr, daemon->addrbuff);
2829 else
2830 safe_strncpy(daemon->addrbuff, s->interface, ADDRSTRLEN);
2831
2832 my_syslog(LOG_ERR, _("failed to bind server socket to %s: %s"),
2833 daemon->addrbuff, strerror(errno));
2834 }
2835
2836 close(fd);
2837 }
2838
2839 return -1;
2840 }
2841
2842 /* compare source addresses and interface, serv2 can be null. */
2843 static int server_isequal(const struct server *serv1,
2844 const struct server *serv2)
2845 {
2846 return (serv2 &&
2847 serv2->ifindex == serv1->ifindex &&
2848 sockaddr_isequal(&serv2->source_addr, &serv1->source_addr) &&
2849 strncmp(serv2->interface, serv1->interface, IF_NAMESIZE) == 0);
2850 }
2851
2852 /* fdlp points to chain of randomfds already in use by transaction.
2853 If there's already a suitable one, return it, else allocate a
2854 new one and add it to the list.
2855
2856 Not leaking any resources in the face of allocation failures
2857 is rather convoluted here.
2858
2859 Note that rfd->serv may be NULL, when a server goes away.
2860 */
2861 int allocate_rfd(struct randfd_list **fdlp, struct server *serv)
2862 {
2863 static int finger = 0;
2864 int i, j = 0;
2865 int ports_full = 0;
2866 struct randfd_list **up, *rfl, *found, **found_link;
2867 struct randfd *rfd = NULL;
2868 int fd = 0;
2869 int ports_avail = 0;
2870
2871 /* We can't have more randomsocks for this AF available than ports in our port range,
2872 so check that here, to avoid trying and failing to bind every port
2873 in local_bind(), called from random_sock(). The actual check is below when
2874 ports_avail != 0 */
2875 if (daemon->max_port != 0)
2876 {
2877 ports_avail = daemon->max_port - daemon->min_port + 1;
2878 if (ports_avail >= SMALL_PORT_RANGE)
2879 ports_avail = 0;
2880 }
2881
2882 /* If server has a pre-allocated fd, use that. */
2883 if (serv->sfd)
2884 return serv->sfd->fd;
2885
2886 /* existing suitable random port socket linked to this transaction?
2887 Find the last one in the list and count how many there are. */
2888 for (found = NULL, found_link = NULL, i = 0, up = fdlp, rfl = *fdlp; rfl; up = &rfl->next, rfl = rfl->next)
2889 if (server_isequal(serv, rfl->rfd->serv))
2890 {
2891 i++;
2892 found = rfl;
2893 found_link = up;
2894 }
2895
2896 /* We have the maximum number for this query already. Promote
2897 the last one on the list to the head, to circulate them,
2898 and return it. */
2899 if (found && i >= daemon->randport_limit)
2900 {
2901 *found_link = found->next;
2902 found->next = *fdlp;
2903 *fdlp = found;
2904 return found->rfd->fd;
2905 }
2906
2907 /* check for all available ports in use. */
2908 if (ports_avail != 0)
2909 {
2910 int ports_inuse;
2911
2912 for (ports_inuse = 0, i = 0; i < daemon->numrrand; i++)
2913 if (daemon->randomsocks[i].refcount != 0 &&
2914 daemon->randomsocks[i].serv->source_addr.sa.sa_family == serv->source_addr.sa.sa_family &&
2915 ++ports_inuse >= ports_avail)
2916 {
2917 ports_full = 1;
2918 break;
2919 }
2920 }
2921
2922 /* limit the number of sockets we have open to avoid starvation of
2923 (eg) TFTP. Once we have a reasonable number, randomness should be OK */
2924 if (!ports_full)
2925 for (i = 0; i < daemon->numrrand; i++)
2926 if (daemon->randomsocks[i].refcount == 0)
2927 {
2928 if ((fd = random_sock(serv)) != -1)
2929 {
2930 rfd = &daemon->randomsocks[i];
2931 rfd->serv = serv;
2932 rfd->fd = fd;
2933 rfd->refcount = 1;
2934 }
2935 break;
2936 }
2937
2938 /* No good existing. Need new link. */
2939 if ((rfl = daemon->rfl_spare))
2940 daemon->rfl_spare = rfl->next;
2941 else if (!(rfl = whine_malloc(sizeof(struct randfd_list))))
2942 {
2943 /* malloc failed, don't leak allocated sock */
2944 if (rfd)
2945 {
2946 close(rfd->fd);
2947 rfd->refcount = 0;
2948 }
2949
2950 return -1;
2951 }
2952
2953 /* No free ones or cannot get new socket, grab an existing one */
2954 if (!rfd)
2955 for (j = 0; j < daemon->numrrand; j++)
2956 {
2957 i = (j + finger) % daemon->numrrand;
2958 if (daemon->randomsocks[i].refcount != 0 &&
2959 server_isequal(serv, daemon->randomsocks[i].serv) &&
2960 daemon->randomsocks[i].refcount != 0xfffe)
2961 {
2962 struct randfd_list *rl;
2963 /* Don't pick one we already have. */
2964 for (rl = *fdlp; rl; rl = rl->next)
2965 if (rl->rfd == &daemon->randomsocks[i])
2966 break;
2967
2968 if (!rl)
2969 {
2970 finger = i + 1;
2971 rfd = &daemon->randomsocks[i];
2972 rfd->refcount++;
2973 break;
2974 }
2975 }
2976 }
2977
2978 if (!rfd) /* should be when j == daemon->numrrand */
2979 {
2980 struct randfd_list *rfl_poll;
2981
2982 /* there are no free slots, and non with the same parameters we can piggy-back on.
2983 We're going to have to allocate a new temporary record, distinguished by
2984 refcount == 0xffff. This will exist in the frec randfd list, never be shared,
2985 and be freed when no longer in use. It will also be held on
2986 the daemon->rfl_poll list so the poll system can find it. */
2987
2988 if ((rfl_poll = daemon->rfl_spare))
2989 daemon->rfl_spare = rfl_poll->next;
2990 else
2991 rfl_poll = whine_malloc(sizeof(struct randfd_list));
2992
2993 if (!rfl_poll ||
2994 !(rfd = whine_malloc(sizeof(struct randfd))) ||
2995 (fd = random_sock(serv)) == -1)
2996 {
2997
2998 /* Don't leak anything we may already have */
2999 rfl->next = daemon->rfl_spare;
3000 daemon->rfl_spare = rfl;
3001
3002 if (rfl_poll)
3003 {
3004 rfl_poll->next = daemon->rfl_spare;
3005 daemon->rfl_spare = rfl_poll;
3006 }
3007
3008 if (rfd)
3009 free(rfd);
3010
3011 return -1; /* doom */
3012 }
3013
3014 /* Note rfd->serv not set here, since it's not reused */
3015 rfd->fd = fd;
3016 rfd->refcount = 0xffff; /* marker for temp record */
3017
3018 rfl_poll->rfd = rfd;
3019 rfl_poll->next = daemon->rfl_poll;
3020 daemon->rfl_poll = rfl_poll;
3021 }
3022
3023 rfl->rfd = rfd;
3024 rfl->next = *fdlp;
3025 *fdlp = rfl;
3026
3027 return rfl->rfd->fd;
3028 }
3029
3030 void free_rfds(struct randfd_list **fdlp)
3031 {
3032 struct randfd_list *tmp, *rfl, *poll, *next, **up;
3033
3034 for (rfl = *fdlp; rfl; rfl = tmp)
3035 {
3036 if (rfl->rfd->refcount == 0xffff || --(rfl->rfd->refcount) == 0)
3037 close(rfl->rfd->fd);
3038
3039 /* temporary overflow record */
3040 if (rfl->rfd->refcount == 0xffff)
3041 {
3042 free(rfl->rfd);
3043
3044 /* go through the link of all these by steam to delete.
3045 This list is expected to be almost always empty. */
3046 for (poll = daemon->rfl_poll, up = &daemon->rfl_poll; poll; poll = next)
3047 {
3048 next = poll->next;
3049
3050 if (poll->rfd == rfl->rfd)
3051 {
3052 *up = poll->next;
3053 poll->next = daemon->rfl_spare;
3054 daemon->rfl_spare = poll;
3055 }
3056 else
3057 up = &poll->next;
3058 }
3059 }
3060
3061 tmp = rfl->next;
3062 rfl->next = daemon->rfl_spare;
3063 daemon->rfl_spare = rfl;
3064 }
3065
3066 *fdlp = NULL;
3067 }
3068
3069 static void free_frec(struct frec *f)
3070 {
3071 struct frec_src *last;
3072
3073 /* add back to freelist if not the record builtin to every frec,
3074 also free any bigmaps they've been decorated with. */
3075 for (last = f->frec_src.next; last && last->next; last = last->next)
3076 if (last->encode_bigmap)
3077 {
3078 free(last->encode_bigmap);
3079 last->encode_bigmap = NULL;
3080 }
3081
3082 if (last)
3083 {
3084 /* final link in the chain loses bigmap too. */
3085 if (last->encode_bigmap)
3086 {
3087 free(last->encode_bigmap);
3088 last->encode_bigmap = NULL;
3089 }
3090 last->next = daemon->free_frec_src;
3091 daemon->free_frec_src = f->frec_src.next;
3092 }
3093
3094 f->frec_src.next = NULL;
3095 free_rfds(&f->rfds);
3096 f->sentto = NULL;
3097 f->flags = 0;
3098
3099 if (f->stash)
3100 {
3101 blockdata_free(f->stash);
3102 f->stash = NULL;
3103 }
3104
3105 #ifdef HAVE_DNSSEC
3106 /* Anything we're waiting on is pointless now, too */
3107 if (f->blocking_query)
3108 {
3109 struct frec *n, **up;
3110
3111 /* unlink outselves from the blocking query's dependents list. */
3112 for (n = f->blocking_query->dependent, up = &f->blocking_query->dependent; n; n = n->next_dependent)
3113 if (n == f)
3114 {
3115 *up = n->next_dependent;
3116 break;
3117 }
3118 else
3119 up = &n->next_dependent;
3120
3121 /* If we were the only/last dependent, free the blocking query too. */
3122 if (!f->blocking_query->dependent)
3123 free_frec(f->blocking_query);
3124 }
3125
3126 f->blocking_query = NULL;
3127 f->dependent = NULL;
3128 f->next_dependent = NULL;
3129 #endif
3130 }
3131
3132
3133
3134 /* Impose an absolute
3135 limit of 4*TIMEOUT before we wipe things (for random sockets).
3136 If force is set, always return a result, even if we have
3137 to allocate above the limit, and don't free any records.
3138 This is set when allocating for DNSSEC to avoid cutting off
3139 the branch we are sitting on. */
3140 static struct frec *get_new_frec(time_t now, struct server *master, int force)
3141 {
3142 struct frec *f, *oldest, *target;
3143 int count;
3144 #ifdef HAVE_DNSSEC
3145 static int next_uid = 0;
3146 #endif
3147
3148 /* look for free records, garbage collect old records and count number in use by our server-group. */
3149 for (f = daemon->frec_list, oldest = NULL, target = NULL, count = 0; f; f = f->next)
3150 {
3151 if (!f->sentto)
3152 target = f;
3153 else
3154 {
3155 #ifdef HAVE_DNSSEC
3156 /* Don't free DNSSEC sub-queries here, as we may end up with
3157 dangling references to them. They'll go when their "real" query
3158 is freed. */
3159 if (!f->dependent)
3160 #endif
3161 if (!force)
3162 {
3163 if (difftime(now, f->time) >= 4*TIMEOUT)
3164 {
3165 daemon->metrics[METRIC_DNS_UNANSWERED_QUERY]++;
3166 free_frec(f);
3167 target = f;
3168 }
3169 else if (!oldest || difftime(f->time, oldest->time) <= 0)
3170 oldest = f;
3171 }
3172 }
3173
3174 if (f->sentto && ((int)difftime(now, f->time)) < TIMEOUT && server_samegroup(f->sentto, master))
3175 count++;
3176 }
3177
3178 if (!force)
3179 {
3180 if (count >= daemon->ftabsize)
3181 {
3182 query_full(now, master->domain);
3183 return NULL;
3184 }
3185
3186 if (!target && oldest && ((int)difftime(now, oldest->time)) >= TIMEOUT)
3187 {
3188 /* can't find empty one, use oldest if there is one and it's older than timeout */
3189 daemon->metrics[METRIC_DNS_UNANSWERED_QUERY]++;
3190 free_frec(oldest);
3191 target = oldest;
3192 }
3193 }
3194
3195 if (!target && (target = (struct frec *)whine_malloc(sizeof(struct frec))))
3196 {
3197 target->next = daemon->frec_list;
3198 daemon->frec_list = target;
3199 }
3200
3201 if (target)
3202 {
3203 target->time = now;
3204 target->forward_delay = daemon->fast_retry_time;
3205 #ifdef HAVE_DNSSEC
3206 target->uid = next_uid++;
3207 #endif
3208 }
3209
3210 return target;
3211 }
3212
3213 static void query_full(time_t now, char *domain)
3214 {
3215 static time_t last_log = 0;
3216
3217 if ((int)difftime(now, last_log) > 5)
3218 {
3219 last_log = now;
3220 if (!domain || strlen(domain) == 0)
3221 my_syslog(LOG_WARNING, _("Maximum number of concurrent DNS queries reached (max: %d)"), daemon->ftabsize);
3222 else
3223 my_syslog(LOG_WARNING, _("Maximum number of concurrent DNS queries to %s reached (max: %d)"), domain, daemon->ftabsize);
3224 }
3225 }
3226
3227 static struct frec *lookup_frec(time_t now, char *target, int class, int rrtype, int id, int flags, int flagmask)
3228 {
3229 struct frec *f;
3230 struct dns_header *header;
3231 int compare_mode = EXTR_NAME_COMPARE;
3232
3233 /* Only compare case-sensitive when matching frec to a received answer,
3234 NOT when looking for a duplicated question. */
3235 if (flags & FREC_ANSWER)
3236 {
3237 flags &= ~FREC_ANSWER;
3238 if (!option_bool(OPT_NO_0x20) && option_bool(OPT_DO_0x20))
3239 compare_mode = EXTR_NAME_NOCASE;
3240 }
3241
3242 for (f = daemon->frec_list; f; f = f->next)
3243 if (f->sentto &&
3244 (f->flags & flagmask) == flags &&
3245 (f->new_id == id || id == -1) &&
3246 (header = blockdata_retrieve(f->stash, f->stash_len, NULL)))
3247 {
3248 unsigned char *p = (unsigned char *)(header+1);
3249 int hclass, hrrtype, rc;
3250
3251 /* Case sensitive compare for DNS-0x20 encoding. */
3252 if ((rc = extract_name(header, f->stash_len, &p, target, compare_mode, 4)))
3253 {
3254 GETSHORT(hrrtype, p);
3255 GETSHORT(hclass, p);
3256
3257 /* type checked by flags for DNSSEC queries. */
3258 if (rrtype != -1 && rrtype != hrrtype)
3259 continue;
3260
3261 if (class != hclass)
3262 continue;
3263 }
3264
3265 if (rc != 1)
3266 {
3267 static int warned = 0;
3268
3269 if (rc == 3 && !warned)
3270 {
3271 my_syslog(LOG_WARNING, _("Case mismatch in DNS reply - check bit 0x20 encoding."));
3272 warned = 1;
3273 }
3274
3275 continue;
3276 }
3277
3278 /* frecs older than this will get garbage-collected in
3279 get_new_frec(), so don't return them here, so we have
3280 consistent behaviour from an idle dnsmasq which
3281 is not calling get_new_frec() often. */
3282 if (difftime(now, f->time) >= 4*TIMEOUT)
3283 return NULL;
3284
3285 return f;
3286 }
3287
3288 return NULL;
3289 }
3290
3291 /* Send query packet again, if we can. */
3292 void resend_query(void)
3293 {
3294 if (daemon->srv_save)
3295 server_send(daemon->srv_save, daemon->fd_save,
3296 daemon->packet, daemon->packet_len);
3297 }
3298
3299 /* A server record is going away, remove references to it */
3300 void server_gone(struct server *server)
3301 {
3302 struct frec *f;
3303 int i;
3304
3305 for (f = daemon->frec_list; f; f = f->next)
3306 if (f->sentto && f->sentto == server)
3307 free_frec(f);
3308
3309 /* If any random socket refers to this server, NULL the reference.
3310 No more references to the socket will be created in the future. */
3311 for (i = 0; i < daemon->numrrand; i++)
3312 if (daemon->randomsocks[i].refcount != 0 && daemon->randomsocks[i].serv == server)
3313 daemon->randomsocks[i].serv = NULL;
3314
3315 if (daemon->srv_save == server)
3316 daemon->srv_save = NULL;
3317 }
3318
3319 /* return unique random ids. */
3320 static unsigned short get_id(void)
3321 {
3322 unsigned short ret = 0;
3323 struct frec *f;
3324
3325 while (1)
3326 {
3327 ret = rand16();
3328
3329 /* ensure id is unique. */
3330 for (f = daemon->frec_list; f; f = f->next)
3331 if (f->sentto && f->new_id == ret)
3332 break;
3333
3334 if (!f)
3335 return ret;
3336 }
3337 }