[powerpc] No need to enter "Ignore Exceptions Mode"
[glibc.git] / support / resolv_test.c
blobaeca519ee3a29d791c93edfb8fb3a0968aac23b3
1 /* DNS test framework and libresolv redirection.
2 Copyright (C) 2016-2019 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <https://www.gnu.org/licenses/>. */
19 #include <support/resolv_test.h>
21 #include <arpa/inet.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <nss.h>
25 #include <resolv.h>
26 #include <search.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <support/check.h>
30 #include <support/namespace.h>
31 #include <support/support.h>
32 #include <support/test-driver.h>
33 #include <support/xsocket.h>
34 #include <support/xthread.h>
35 #include <support/xunistd.h>
36 #include <sys/uio.h>
37 #include <unistd.h>
39 /* Response builder. */
41 enum
43 max_response_length = 65536
46 /* Used for locating domain names containing for the purpose of
47 forming compression references. */
48 struct compressed_name
50 uint16_t offset;
51 unsigned char length;
52 unsigned char name[]; /* Without terminating NUL. */
55 static struct compressed_name *
56 allocate_compressed_name (const unsigned char *encoded, unsigned int offset)
58 /* Compute the length of the domain name. */
59 size_t length;
61 const unsigned char *p;
62 for (p = encoded; *p != '\0';)
64 /* No compression references are allowed. */
65 TEST_VERIFY (*p <= 63);
66 /* Skip over the label. */
67 p += 1 + *p;
69 length = p - encoded;
70 ++length; /* For the terminating NUL byte. */
72 TEST_VERIFY_EXIT (length <= 255);
74 struct compressed_name *result
75 = xmalloc (offsetof (struct compressed_name, name) + length);
76 result->offset = offset;
77 result->length = length;
78 memcpy (result->name, encoded, length);
79 return result;
82 /* Convert CH to lower case. Only change letters in the ASCII
83 range. */
84 static inline unsigned char
85 ascii_tolower (unsigned char ch)
87 if ('A' <= ch && ch <= 'Z')
88 return ch - 'A' + 'a';
89 else
90 return ch;
93 /* Compare both names, for use with tsearch. The order is arbitrary,
94 but the comparison is case-insenstive. */
95 static int
96 compare_compressed_name (const void *left, const void *right)
98 const struct compressed_name *crleft = left;
99 const struct compressed_name *crright = right;
101 if (crleft->length != crright->length)
102 /* The operands are converted to int before the subtraction. */
103 return crleft->length - crright->length;
105 const unsigned char *nameleft = crleft->name;
106 const unsigned char *nameright = crright->name;
108 while (true)
110 int lenleft = *nameleft++;
111 int lenright = *nameright++;
113 /* Labels must not e compression references. */
114 TEST_VERIFY (lenleft <= 63);
115 TEST_VERIFY (lenright <= 63);
117 if (lenleft != lenright)
118 return left - right;
119 if (lenleft == 0)
120 /* End of name reached without spotting a difference. */
121 return 0;
122 /* Compare the label in a case-insenstive manner. */
123 const unsigned char *endnameleft = nameleft + lenleft;
124 while (nameleft < endnameleft)
126 int l = *nameleft++;
127 int r = *nameright++;
128 if (l != r)
130 l = ascii_tolower (l);
131 r = ascii_tolower (r);
132 if (l != r)
133 return l - r;
139 struct resolv_response_builder
141 const unsigned char *query_buffer;
142 size_t query_length;
144 size_t offset; /* Bytes written so far in buffer. */
145 ns_sect section; /* Current section in the DNS packet. */
146 unsigned int truncate_bytes; /* Bytes to remove at end of response. */
147 bool drop; /* Discard generated response. */
148 bool close; /* Close TCP client connection. */
150 /* Offset of the two-byte RDATA length field in the currently
151 written RDATA sub-structure. 0 if no RDATA is being written. */
152 size_t current_rdata_offset;
154 /* tsearch tree for locating targets for label compression. */
155 void *compression_offsets;
157 /* Must be last. Not zeroed for performance reasons. */
158 unsigned char buffer[max_response_length];
161 /* Response builder. */
163 void
164 resolv_response_init (struct resolv_response_builder *b,
165 struct resolv_response_flags flags)
167 if (b->offset > 0)
168 FAIL_EXIT1 ("response_init: called at offset %zu", b->offset);
169 if (b->query_length < 12)
170 FAIL_EXIT1 ("response_init called for a query of size %zu",
171 b->query_length);
172 if (flags.rcode > 15)
173 FAIL_EXIT1 ("response_init: invalid RCODE %u", flags.rcode);
175 /* Copy the transaction ID. */
176 b->buffer[0] = b->query_buffer[0];
177 b->buffer[1] = b->query_buffer[1];
179 /* Initialize the flags. */
180 b->buffer[2] = 0x80; /* Mark as response. */
181 b->buffer[2] |= b->query_buffer[2] & 0x01; /* Copy the RD bit. */
182 if (flags.tc)
183 b->buffer[2] |= 0x02;
184 b->buffer[3] = 0x80 | flags.rcode; /* Always set RA. */
186 /* Fill in the initial section count values. */
187 b->buffer[4] = flags.qdcount >> 8;
188 b->buffer[5] = flags.qdcount;
189 b->buffer[6] = flags.ancount >> 8;
190 b->buffer[7] = flags.ancount;
191 b->buffer[8] = flags.nscount >> 8;
192 b->buffer[9] = flags.nscount;
193 b->buffer[10] = flags.adcount >> 8;
194 b->buffer[11] = flags.adcount;
196 b->offset = 12;
199 void
200 resolv_response_section (struct resolv_response_builder *b, ns_sect section)
202 if (b->offset == 0)
203 FAIL_EXIT1 ("resolv_response_section: response_init not called before");
204 if (section < b->section)
205 FAIL_EXIT1 ("resolv_response_section: cannot go back to previous section");
206 b->section = section;
209 /* Add a single byte to B. */
210 static inline void
211 response_add_byte (struct resolv_response_builder *b, unsigned char ch)
213 if (b->offset == max_response_length)
214 FAIL_EXIT1 ("DNS response exceeds 64 KiB limit");
215 b->buffer[b->offset] = ch;
216 ++b->offset;
219 /* Add a 16-bit word VAL to B, in big-endian format. */
220 static void
221 response_add_16 (struct resolv_response_builder *b, uint16_t val)
223 response_add_byte (b, val >> 8);
224 response_add_byte (b, val);
227 /* Increment the pers-section record counter in the packet header. */
228 static void
229 response_count_increment (struct resolv_response_builder *b)
231 unsigned int offset = b->section;
232 offset = 4 + 2 * offset;
233 ++b->buffer[offset + 1];
234 if (b->buffer[offset + 1] == 0)
236 /* Carry. */
237 ++b->buffer[offset];
238 if (b->buffer[offset] == 0)
239 /* Overflow. */
240 FAIL_EXIT1 ("too many records in section");
244 void
245 resolv_response_add_question (struct resolv_response_builder *b,
246 const char *name, uint16_t class, uint16_t type)
248 if (b->offset == 0)
249 FAIL_EXIT1 ("resolv_response_add_question: "
250 "resolv_response_init not called");
251 if (b->section != ns_s_qd)
252 FAIL_EXIT1 ("resolv_response_add_question: "
253 "must be called in the question section");
255 resolv_response_add_name (b, name);
256 response_add_16 (b, type);
257 response_add_16 (b, class);
259 response_count_increment (b);
262 void
263 resolv_response_add_name (struct resolv_response_builder *b,
264 const char *const origname)
266 unsigned char encoded_name[NS_MAXDNAME];
267 if (ns_name_pton (origname, encoded_name, sizeof (encoded_name)) < 0)
268 FAIL_EXIT1 ("ns_name_pton (\"%s\"): %m", origname);
270 /* Copy the encoded name into the output buffer, apply compression
271 where possible. */
272 for (const unsigned char *name = encoded_name; ;)
274 if (*name == '\0')
276 /* We have reached the end of the name. Add the terminating
277 NUL byte. */
278 response_add_byte (b, '\0');
279 break;
282 /* Set to the compression target if compression is possible. */
283 struct compressed_name *crname_target;
285 /* Compression references can only reach the beginning of the
286 packet. */
287 enum { compression_limit = 1 << 12 };
290 /* The trailing part of the name to be looked up in the tree
291 with the compression targets. */
292 struct compressed_name *crname
293 = allocate_compressed_name (name, b->offset);
295 if (b->offset < compression_limit)
297 /* Add the name to the tree, for future compression
298 references. */
299 void **ptr = tsearch (crname, &b->compression_offsets,
300 compare_compressed_name);
301 if (ptr == NULL)
302 FAIL_EXIT1 ("tsearch out of memory");
303 crname_target = *ptr;
305 if (crname_target != crname)
306 /* The new name was not actually added to the tree.
307 Deallocate it. */
308 free (crname);
309 else
310 /* Signal that the tree did not yet contain the name,
311 but keep the allocation because it is now part of the
312 tree. */
313 crname_target = NULL;
315 else
317 /* This name cannot be reached by a compression reference.
318 No need to add it to the tree for future reference. */
319 void **ptr = tfind (crname, &b->compression_offsets,
320 compare_compressed_name);
321 if (ptr != NULL)
322 crname_target = *ptr;
323 else
324 crname_target = NULL;
325 TEST_VERIFY (crname_target != crname);
326 /* Not added to the tree. */
327 free (crname);
331 if (crname_target != NULL)
333 /* The name is known. Reference the previous location. */
334 unsigned int old_offset = crname_target->offset;
335 TEST_VERIFY_EXIT (old_offset < compression_limit);
336 response_add_byte (b, 0xC0 | (old_offset >> 8));
337 response_add_byte (b, old_offset);
338 break;
340 else
342 /* The name is new. Add this label. */
343 unsigned int len = 1 + *name;
344 resolv_response_add_data (b, name, len);
345 name += len;
350 void
351 resolv_response_open_record (struct resolv_response_builder *b,
352 const char *name,
353 uint16_t class, uint16_t type, uint32_t ttl)
355 if (b->section == ns_s_qd)
356 FAIL_EXIT1 ("resolv_response_open_record called in question section");
357 if (b->current_rdata_offset != 0)
358 FAIL_EXIT1 ("resolv_response_open_record called with open record");
360 resolv_response_add_name (b, name);
361 response_add_16 (b, type);
362 response_add_16 (b, class);
363 response_add_16 (b, ttl >> 16);
364 response_add_16 (b, ttl);
366 b->current_rdata_offset = b->offset;
367 /* Add room for the RDATA length. */
368 response_add_16 (b, 0);
372 void
373 resolv_response_close_record (struct resolv_response_builder *b)
375 size_t rdata_offset = b->current_rdata_offset;
376 if (rdata_offset == 0)
377 FAIL_EXIT1 ("response_close_record called without open record");
378 size_t rdata_length = b->offset - rdata_offset - 2;
379 if (rdata_length > 65535)
380 FAIL_EXIT1 ("RDATA length %zu exceeds limit", rdata_length);
381 b->buffer[rdata_offset] = rdata_length >> 8;
382 b->buffer[rdata_offset + 1] = rdata_length;
383 response_count_increment (b);
384 b->current_rdata_offset = 0;
387 void
388 resolv_response_add_data (struct resolv_response_builder *b,
389 const void *data, size_t length)
391 size_t remaining = max_response_length - b->offset;
392 if (remaining < length)
393 FAIL_EXIT1 ("resolv_response_add_data: not enough room for %zu bytes",
394 length);
395 memcpy (b->buffer + b->offset, data, length);
396 b->offset += length;
399 void
400 resolv_response_drop (struct resolv_response_builder *b)
402 b->drop = true;
405 void
406 resolv_response_close (struct resolv_response_builder *b)
408 b->close = true;
411 void
412 resolv_response_truncate_data (struct resolv_response_builder *b, size_t count)
414 if (count > 65535)
415 FAIL_EXIT1 ("resolv_response_truncate_data: argument too large: %zu",
416 count);
417 b->truncate_bytes = count;
421 size_t
422 resolv_response_length (const struct resolv_response_builder *b)
424 return b->offset;
427 unsigned char *
428 resolv_response_buffer (const struct resolv_response_builder *b)
430 unsigned char *result = xmalloc (b->offset);
431 memcpy (result, b->buffer, b->offset);
432 return result;
435 static struct resolv_response_builder *
436 response_builder_allocate
437 (const unsigned char *query_buffer, size_t query_length)
439 struct resolv_response_builder *b = xmalloc (sizeof (*b));
440 memset (b, 0, offsetof (struct resolv_response_builder, buffer));
441 b->query_buffer = query_buffer;
442 b->query_length = query_length;
443 return b;
446 static void
447 response_builder_free (struct resolv_response_builder *b)
449 tdestroy (b->compression_offsets, free);
450 free (b);
453 /* DNS query processing. */
455 /* Data extracted from the question section of a DNS packet. */
456 struct query_info
458 char qname[MAXDNAME];
459 uint16_t qclass;
460 uint16_t qtype;
461 struct resolv_edns_info edns;
464 /* Update *INFO from the specified DNS packet. */
465 static void
466 parse_query (struct query_info *info,
467 const unsigned char *buffer, size_t length)
469 HEADER hd;
470 _Static_assert (sizeof (hd) == 12, "DNS header size");
471 if (length < sizeof (hd))
472 FAIL_EXIT1 ("malformed DNS query: too short: %zu bytes", length);
473 memcpy (&hd, buffer, sizeof (hd));
475 if (ntohs (hd.qdcount) != 1)
476 FAIL_EXIT1 ("malformed DNS query: wrong question count: %d",
477 (int) ntohs (hd.qdcount));
478 if (ntohs (hd.ancount) != 0)
479 FAIL_EXIT1 ("malformed DNS query: wrong answer count: %d",
480 (int) ntohs (hd.ancount));
481 if (ntohs (hd.nscount) != 0)
482 FAIL_EXIT1 ("malformed DNS query: wrong authority count: %d",
483 (int) ntohs (hd.nscount));
484 if (ntohs (hd.arcount) > 1)
485 FAIL_EXIT1 ("malformed DNS query: wrong additional count: %d",
486 (int) ntohs (hd.arcount));
488 int ret = dn_expand (buffer, buffer + length, buffer + sizeof (hd),
489 info->qname, sizeof (info->qname));
490 if (ret < 0)
491 FAIL_EXIT1 ("malformed DNS query: cannot uncompress QNAME");
493 /* Obtain QTYPE and QCLASS. */
494 size_t remaining = length - (12 + ret);
495 struct
497 uint16_t qtype;
498 uint16_t qclass;
499 } qtype_qclass;
500 if (remaining < sizeof (qtype_qclass))
501 FAIL_EXIT1 ("malformed DNS query: "
502 "query lacks QCLASS/QTYPE, QNAME: %s", info->qname);
503 memcpy (&qtype_qclass, buffer + 12 + ret, sizeof (qtype_qclass));
504 info->qclass = ntohs (qtype_qclass.qclass);
505 info->qtype = ntohs (qtype_qclass.qtype);
507 memset (&info->edns, 0, sizeof (info->edns));
508 if (ntohs (hd.arcount) > 0)
510 /* Parse EDNS record. */
511 struct __attribute__ ((packed, aligned (1)))
513 uint8_t root;
514 uint16_t rtype;
515 uint16_t payload;
516 uint8_t edns_extended_rcode;
517 uint8_t edns_version;
518 uint16_t flags;
519 uint16_t rdatalen;
520 } rr;
521 _Static_assert (sizeof (rr) == 11, "EDNS record size");
523 if (remaining < 4 + sizeof (rr))
524 FAIL_EXIT1 ("mailformed DNS query: no room for EDNS record");
525 memcpy (&rr, buffer + 12 + ret + 4, sizeof (rr));
526 if (rr.root != 0)
527 FAIL_EXIT1 ("malformed DNS query: invalid OPT RNAME: %d\n", rr.root);
528 if (rr.rtype != htons (41))
529 FAIL_EXIT1 ("malformed DNS query: invalid OPT type: %d\n",
530 ntohs (rr.rtype));
531 info->edns.active = true;
532 info->edns.extended_rcode = rr.edns_extended_rcode;
533 info->edns.version = rr.edns_version;
534 info->edns.flags = ntohs (rr.flags);
535 info->edns.payload_size = ntohs (rr.payload);
540 /* Main testing framework. */
542 /* Per-server information. One struct is allocated for each test
543 server. */
544 struct resolv_test_server
546 /* Local address of the server. UDP and TCP use the same port. */
547 struct sockaddr_in address;
549 /* File descriptor of the UDP server, or -1 if this server is
550 disabled. */
551 int socket_udp;
553 /* File descriptor of the TCP server, or -1 if this server is
554 disabled. */
555 int socket_tcp;
557 /* Counter of the number of responses processed so far. */
558 size_t response_number;
560 /* Thread handles for the server threads (if not disabled in the
561 configuration). */
562 pthread_t thread_udp;
563 pthread_t thread_tcp;
566 /* Main struct for keeping track of libresolv redirection and
567 testing. */
568 struct resolv_test
570 /* After initialization, any access to the struct must be performed
571 while this lock is acquired. */
572 pthread_mutex_t lock;
574 /* Data for each test server. */
575 struct resolv_test_server servers[resolv_max_test_servers];
577 /* Used if config.single_thread_udp is true. */
578 pthread_t thread_udp_single;
580 struct resolv_redirect_config config;
581 bool termination_requested;
584 /* Function implementing a server thread. */
585 typedef void (*thread_callback) (struct resolv_test *, int server_index);
587 /* Storage for thread-specific data, for passing to the
588 thread_callback function. */
589 struct thread_closure
591 struct resolv_test *obj; /* Current test object. */
592 thread_callback callback; /* Function to call. */
593 int server_index; /* Index of the implemented server. */
596 /* Wrap response_callback as a function which can be passed to
597 pthread_create. */
598 static void *
599 thread_callback_wrapper (void *arg)
601 struct thread_closure *closure = arg;
602 closure->callback (closure->obj, closure->server_index);
603 free (closure);
604 return NULL;
607 /* Start a server thread for the specified SERVER_INDEX, implemented
608 by CALLBACK. */
609 static pthread_t
610 start_server_thread (struct resolv_test *obj, int server_index,
611 thread_callback callback)
613 struct thread_closure *closure = xmalloc (sizeof (*closure));
614 *closure = (struct thread_closure)
616 .obj = obj,
617 .callback = callback,
618 .server_index = server_index,
620 return xpthread_create (NULL, thread_callback_wrapper, closure);
623 /* Process one UDP query. Return false if a termination requested has
624 been detected. */
625 static bool
626 server_thread_udp_process_one (struct resolv_test *obj, int server_index)
628 unsigned char query[512];
629 struct sockaddr_storage peer;
630 socklen_t peerlen = sizeof (peer);
631 size_t length = xrecvfrom (obj->servers[server_index].socket_udp,
632 query, sizeof (query), 0,
633 (struct sockaddr *) &peer, &peerlen);
634 /* Check for termination. */
636 bool termination_requested;
637 xpthread_mutex_lock (&obj->lock);
638 termination_requested = obj->termination_requested;
639 xpthread_mutex_unlock (&obj->lock);
640 if (termination_requested)
641 return false;
645 struct query_info qinfo;
646 parse_query (&qinfo, query, length);
647 if (test_verbose > 0)
649 if (test_verbose > 1)
650 printf ("info: UDP server %d: incoming query:"
651 " %zd bytes, %s/%u/%u, tnxid=0x%02x%02x\n",
652 server_index, length, qinfo.qname, qinfo.qclass, qinfo.qtype,
653 query[0], query[1]);
654 else
655 printf ("info: UDP server %d: incoming query:"
656 " %zd bytes, %s/%u/%u\n",
657 server_index, length, qinfo.qname, qinfo.qclass, qinfo.qtype);
660 struct resolv_response_context ctx =
662 .query_buffer = query,
663 .query_length = length,
664 .server_index = server_index,
665 .tcp = false,
666 .edns = qinfo.edns,
668 struct resolv_response_builder *b = response_builder_allocate (query, length);
669 obj->config.response_callback
670 (&ctx, b, qinfo.qname, qinfo.qclass, qinfo.qtype);
672 if (b->drop)
674 if (test_verbose)
675 printf ("info: UDP server %d: dropping response to %s/%u/%u\n",
676 server_index, qinfo.qname, qinfo.qclass, qinfo.qtype);
678 else
680 if (test_verbose)
682 if (b->offset >= 12)
683 printf ("info: UDP server %d: sending response:"
684 " %zu bytes, RCODE %d (for %s/%u/%u)\n",
685 server_index, b->offset, b->buffer[3] & 0x0f,
686 qinfo.qname, qinfo.qclass, qinfo.qtype);
687 else
688 printf ("info: UDP server %d: sending response: %zu bytes"
689 " (for %s/%u/%u)\n",
690 server_index, b->offset,
691 qinfo.qname, qinfo.qclass, qinfo.qtype);
692 if (b->truncate_bytes > 0)
693 printf ("info: truncated by %u bytes\n", b->truncate_bytes);
695 size_t to_send = b->offset;
696 if (to_send < b->truncate_bytes)
697 to_send = 0;
698 else
699 to_send -= b->truncate_bytes;
701 /* Ignore most errors here because the other end may have closed
702 the socket. */
703 if (sendto (obj->servers[server_index].socket_udp,
704 b->buffer, to_send, 0,
705 (struct sockaddr *) &peer, peerlen) < 0)
706 TEST_VERIFY_EXIT (errno != EBADF);
708 response_builder_free (b);
709 return true;
712 /* UDP thread_callback function. Variant for one thread per
713 server. */
714 static void
715 server_thread_udp (struct resolv_test *obj, int server_index)
717 while (server_thread_udp_process_one (obj, server_index))
721 /* Single-threaded UDP processing function, for the single_thread_udp
722 case. */
723 static void *
724 server_thread_udp_single (void *closure)
726 struct resolv_test *obj = closure;
728 struct pollfd fds[resolv_max_test_servers];
729 for (int server_index = 0; server_index < resolv_max_test_servers;
730 ++server_index)
731 if (obj->config.servers[server_index].disable_udp)
732 fds[server_index] = (struct pollfd) {.fd = -1};
733 else
735 fds[server_index] = (struct pollfd)
737 .fd = obj->servers[server_index].socket_udp,
738 .events = POLLIN
741 /* Make the socket non-blocking. */
742 int flags = fcntl (obj->servers[server_index].socket_udp, F_GETFL, 0);
743 if (flags < 0)
744 FAIL_EXIT1 ("fcntl (F_GETFL): %m");
745 flags |= O_NONBLOCK;
746 if (fcntl (obj->servers[server_index].socket_udp, F_SETFL, flags) < 0)
747 FAIL_EXIT1 ("fcntl (F_SETFL): %m");
750 while (true)
752 xpoll (fds, resolv_max_test_servers, -1);
753 for (int server_index = 0; server_index < resolv_max_test_servers;
754 ++server_index)
755 if (fds[server_index].revents != 0)
757 if (!server_thread_udp_process_one (obj, server_index))
758 goto out;
759 fds[server_index].revents = 0;
763 out:
764 return NULL;
767 /* Start the single UDP handler thread (for the single_thread_udp
768 case). */
769 static void
770 start_server_thread_udp_single (struct resolv_test *obj)
772 obj->thread_udp_single
773 = xpthread_create (NULL, server_thread_udp_single, obj);
776 /* Data describing a TCP client connect. */
777 struct tcp_thread_closure
779 struct resolv_test *obj;
780 int server_index;
781 int client_socket;
784 /* Read a complete DNS query packet. If EOF_OK, an immediate
785 end-of-file condition is acceptable. */
786 static bool
787 read_fully (int fd, void *buf, size_t len, bool eof_ok)
789 const void *const end = buf + len;
790 while (buf < end)
792 ssize_t ret = read (fd, buf, end - buf);
793 if (ret == 0)
795 if (!eof_ok)
797 support_record_failure ();
798 printf ("error: unexpected EOF on TCP connection\n");
800 return false;
802 else if (ret < 0)
804 if (!eof_ok || errno != ECONNRESET)
806 support_record_failure ();
807 printf ("error: TCP read: %m\n");
809 return false;
811 buf += ret;
812 eof_ok = false;
814 return true;
817 /* Write an array of iovecs. Terminate the process on failure. */
818 static void
819 writev_fully (int fd, struct iovec *buffers, size_t count)
821 while (count > 0)
823 /* Skip zero-length write requests. */
824 if (buffers->iov_len == 0)
826 ++buffers;
827 --count;
828 continue;
830 /* Try to rewrite the remaing buffers. */
831 ssize_t ret = writev (fd, buffers, count);
832 if (ret < 0)
833 FAIL_EXIT1 ("writev: %m");
834 if (ret == 0)
835 FAIL_EXIT1 ("writev: invalid return value zero");
836 /* Find the buffers that were successfully written. */
837 while (ret > 0)
839 if (count == 0)
840 FAIL_EXIT1 ("internal writev consistency failure");
841 /* Current buffer was partially written. */
842 if (buffers->iov_len > (size_t) ret)
844 buffers->iov_base += ret;
845 buffers->iov_len -= ret;
846 ret = 0;
848 else
850 ret -= buffers->iov_len;
851 buffers->iov_len = 0;
852 ++buffers;
853 --count;
859 /* Thread callback for handling a single established TCP connection to
860 a client. */
861 static void *
862 server_thread_tcp_client (void *arg)
864 struct tcp_thread_closure *closure = arg;
866 while (true)
868 /* Read packet length. */
869 uint16_t query_length;
870 if (!read_fully (closure->client_socket,
871 &query_length, sizeof (query_length), true))
872 break;
873 query_length = ntohs (query_length);
875 /* Read the packet. */
876 unsigned char *query_buffer = xmalloc (query_length);
877 read_fully (closure->client_socket, query_buffer, query_length, false);
879 struct query_info qinfo;
880 parse_query (&qinfo, query_buffer, query_length);
881 if (test_verbose > 0)
883 if (test_verbose > 1)
884 printf ("info: UDP server %d: incoming query:"
885 " %d bytes, %s/%u/%u, tnxid=0x%02x%02x\n",
886 closure->server_index, query_length,
887 qinfo.qname, qinfo.qclass, qinfo.qtype,
888 query_buffer[0], query_buffer[1]);
889 else
890 printf ("info: TCP server %d: incoming query:"
891 " %u bytes, %s/%u/%u\n",
892 closure->server_index, query_length,
893 qinfo.qname, qinfo.qclass, qinfo.qtype);
896 struct resolv_response_context ctx =
898 .query_buffer = query_buffer,
899 .query_length = query_length,
900 .server_index = closure->server_index,
901 .tcp = true,
902 .edns = qinfo.edns,
904 struct resolv_response_builder *b = response_builder_allocate
905 (query_buffer, query_length);
906 closure->obj->config.response_callback
907 (&ctx, b, qinfo.qname, qinfo.qclass, qinfo.qtype);
909 if (b->drop)
911 if (test_verbose)
912 printf ("info: TCP server %d: dropping response to %s/%u/%u\n",
913 closure->server_index,
914 qinfo.qname, qinfo.qclass, qinfo.qtype);
916 else
918 if (test_verbose)
919 printf ("info: TCP server %d: sending response: %zu bytes"
920 " (for %s/%u/%u)\n",
921 closure->server_index, b->offset,
922 qinfo.qname, qinfo.qclass, qinfo.qtype);
923 uint16_t length = htons (b->offset);
924 size_t to_send = b->offset;
925 if (to_send < b->truncate_bytes)
926 to_send = 0;
927 else
928 to_send -= b->truncate_bytes;
929 struct iovec buffers[2] =
931 {&length, sizeof (length)},
932 {b->buffer, to_send}
934 writev_fully (closure->client_socket, buffers, 2);
936 bool close_flag = b->close;
937 response_builder_free (b);
938 free (query_buffer);
939 if (close_flag)
940 break;
943 xclose (closure->client_socket);
944 free (closure);
945 return NULL;
948 /* thread_callback for the TCP case. Accept connections and create a
949 new thread for each client. */
950 static void
951 server_thread_tcp (struct resolv_test *obj, int server_index)
953 while (true)
955 /* Get the client conenction. */
956 int client_socket = xaccept
957 (obj->servers[server_index].socket_tcp, NULL, NULL);
959 /* Check for termination. */
960 xpthread_mutex_lock (&obj->lock);
961 if (obj->termination_requested)
963 xpthread_mutex_unlock (&obj->lock);
964 xclose (client_socket);
965 break;
967 xpthread_mutex_unlock (&obj->lock);
969 /* Spawn a new thread for handling this connection. */
970 struct tcp_thread_closure *closure = xmalloc (sizeof (*closure));
971 *closure = (struct tcp_thread_closure)
973 .obj = obj,
974 .server_index = server_index,
975 .client_socket = client_socket,
978 pthread_t thr
979 = xpthread_create (NULL, server_thread_tcp_client, closure);
980 /* TODO: We should keep track of this thread so that we can
981 block in resolv_test_end until it has exited. */
982 xpthread_detach (thr);
986 /* Create UDP and TCP server sockets. */
987 static void
988 make_server_sockets (struct resolv_test_server *server)
990 while (true)
992 server->socket_udp = xsocket (AF_INET, SOCK_DGRAM, IPPROTO_UDP);
993 server->socket_tcp = xsocket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
995 /* Pick the address for the UDP socket. */
996 server->address = (struct sockaddr_in)
998 .sin_family = AF_INET,
999 .sin_addr = {.s_addr = htonl (INADDR_LOOPBACK)}
1001 xbind (server->socket_udp,
1002 (struct sockaddr *)&server->address, sizeof (server->address));
1004 /* Retrieve the address. */
1005 socklen_t addrlen = sizeof (server->address);
1006 xgetsockname (server->socket_udp,
1007 (struct sockaddr *)&server->address, &addrlen);
1009 /* Bind the TCP socket to the same address. */
1011 int on = 1;
1012 xsetsockopt (server->socket_tcp, SOL_SOCKET, SO_REUSEADDR,
1013 &on, sizeof (on));
1015 if (bind (server->socket_tcp,
1016 (struct sockaddr *)&server->address,
1017 sizeof (server->address)) != 0)
1019 /* Port collision. The UDP bind succeeded, but the TCP BIND
1020 failed. We assume here that the kernel will pick the
1021 next local UDP address randomly. */
1022 if (errno == EADDRINUSE)
1024 xclose (server->socket_udp);
1025 xclose (server->socket_tcp);
1026 continue;
1028 FAIL_EXIT1 ("TCP bind: %m");
1030 xlisten (server->socket_tcp, 5);
1031 break;
1035 /* Like make_server_sockets, but the caller supplies the address to
1036 use. */
1037 static void
1038 make_server_sockets_for_address (struct resolv_test_server *server,
1039 const struct sockaddr *addr)
1041 server->socket_udp = xsocket (AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1042 server->socket_tcp = xsocket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1044 if (addr->sa_family == AF_INET)
1045 server->address = *(const struct sockaddr_in *) addr;
1046 else
1047 /* We cannot store the server address in the socket. This should
1048 not matter if disable_redirect is used. */
1049 server->address = (struct sockaddr_in) { .sin_family = 0, };
1051 xbind (server->socket_udp,
1052 (struct sockaddr *)&server->address, sizeof (server->address));
1053 xbind (server->socket_tcp,
1054 (struct sockaddr *)&server->address, sizeof (server->address));
1055 xlisten (server->socket_tcp, 5);
1058 /* One-time initialization of NSS. */
1059 static void
1060 resolv_redirect_once (void)
1062 /* Only use nss_dns. */
1063 __nss_configure_lookup ("hosts", "dns");
1064 __nss_configure_lookup ("networks", "dns");
1065 /* Enter a network namespace for isolation and firewall state
1066 cleanup. The tests will still work if these steps fail, but they
1067 may be less reliable. */
1068 support_become_root ();
1069 support_enter_network_namespace ();
1071 pthread_once_t resolv_redirect_once_var = PTHREAD_ONCE_INIT;
1073 void
1074 resolv_test_init (void)
1076 /* Perform one-time initialization of NSS. */
1077 xpthread_once (&resolv_redirect_once_var, resolv_redirect_once);
1080 /* Copy the search path from CONFIG.search to the _res object. */
1081 static void
1082 set_search_path (struct resolv_redirect_config config)
1084 memset (_res.defdname, 0, sizeof (_res.defdname));
1085 memset (_res.dnsrch, 0, sizeof (_res.dnsrch));
1087 char *current = _res.defdname;
1088 char *end = current + sizeof (_res.defdname);
1090 for (unsigned int i = 0;
1091 i < sizeof (config.search) / sizeof (config.search[0]); ++i)
1093 if (config.search[i] == NULL)
1094 continue;
1096 size_t length = strlen (config.search[i]) + 1;
1097 size_t remaining = end - current;
1098 TEST_VERIFY_EXIT (length <= remaining);
1099 memcpy (current, config.search[i], length);
1100 _res.dnsrch[i] = current;
1101 current += length;
1105 struct resolv_test *
1106 resolv_test_start (struct resolv_redirect_config config)
1108 /* Apply configuration defaults. */
1109 if (config.nscount == 0)
1110 config.nscount = resolv_max_test_servers;
1112 struct resolv_test *obj = xmalloc (sizeof (*obj));
1113 *obj = (struct resolv_test) {
1114 .config = config,
1115 .lock = PTHREAD_MUTEX_INITIALIZER,
1118 if (!config.disable_redirect)
1119 resolv_test_init ();
1121 /* Create all the servers, to reserve the necessary ports. */
1122 for (int server_index = 0; server_index < config.nscount; ++server_index)
1123 if (config.disable_redirect && config.server_address_overrides != NULL)
1124 make_server_sockets_for_address
1125 (obj->servers + server_index,
1126 config.server_address_overrides[server_index]);
1127 else
1128 make_server_sockets (obj->servers + server_index);
1130 /* Start server threads. Disable the server ports, as
1131 requested. */
1132 for (int server_index = 0; server_index < config.nscount; ++server_index)
1134 struct resolv_test_server *server = obj->servers + server_index;
1135 if (config.servers[server_index].disable_udp)
1137 xclose (server->socket_udp);
1138 server->socket_udp = -1;
1140 else if (!config.single_thread_udp)
1141 server->thread_udp = start_server_thread (obj, server_index,
1142 server_thread_udp);
1143 if (config.servers[server_index].disable_tcp)
1145 xclose (server->socket_tcp);
1146 server->socket_tcp = -1;
1148 else
1149 server->thread_tcp = start_server_thread (obj, server_index,
1150 server_thread_tcp);
1152 if (config.single_thread_udp)
1153 start_server_thread_udp_single (obj);
1155 if (config.disable_redirect)
1156 return obj;
1158 int timeout = 1;
1160 /* Initialize libresolv. */
1161 TEST_VERIFY_EXIT (res_init () == 0);
1163 /* Disable IPv6 name server addresses. The code below only
1164 overrides the IPv4 addresses. */
1165 __res_iclose (&_res, true);
1166 _res._u._ext.nscount = 0;
1168 /* Redirect queries to the server socket. */
1169 if (test_verbose)
1171 printf ("info: old timeout value: %d\n", _res.retrans);
1172 printf ("info: old retry attempt value: %d\n", _res.retry);
1173 printf ("info: old _res.options: 0x%lx\n", _res.options);
1174 printf ("info: old _res.nscount value: %d\n", _res.nscount);
1175 printf ("info: old _res.ndots value: %d\n", _res.ndots);
1177 _res.retrans = timeout;
1178 _res.retry = 4;
1179 _res.nscount = config.nscount;
1180 _res.options = RES_INIT | RES_RECURSE | RES_DEFNAMES | RES_DNSRCH;
1181 _res.ndots = 1;
1182 if (test_verbose)
1184 printf ("info: new timeout value: %d\n", _res.retrans);
1185 printf ("info: new retry attempt value: %d\n", _res.retry);
1186 printf ("info: new _res.options: 0x%lx\n", _res.options);
1187 printf ("info: new _res.nscount value: %d\n", _res.nscount);
1188 printf ("info: new _res.ndots value: %d\n", _res.ndots);
1190 for (int server_index = 0; server_index < config.nscount; ++server_index)
1192 TEST_VERIFY_EXIT (obj->servers[server_index].address.sin_port != 0);
1193 _res.nsaddr_list[server_index] = obj->servers[server_index].address;
1194 if (test_verbose)
1196 char buf[256];
1197 TEST_VERIFY_EXIT
1198 (inet_ntop (AF_INET, &obj->servers[server_index].address.sin_addr,
1199 buf, sizeof (buf)) != NULL);
1200 printf ("info: server %d: %s/%u\n",
1201 server_index, buf,
1202 htons (obj->servers[server_index].address.sin_port));
1206 set_search_path (config);
1208 return obj;
1211 void
1212 resolv_test_end (struct resolv_test *obj)
1214 res_close ();
1216 xpthread_mutex_lock (&obj->lock);
1217 obj->termination_requested = true;
1218 xpthread_mutex_unlock (&obj->lock);
1220 /* Send trigger packets to unblock the server threads. */
1221 for (int server_index = 0; server_index < obj->config.nscount;
1222 ++server_index)
1224 if (!obj->config.servers[server_index].disable_udp)
1226 int sock = xsocket (AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1227 xsendto (sock, "", 1, 0,
1228 (struct sockaddr *) &obj->servers[server_index].address,
1229 sizeof (obj->servers[server_index].address));
1230 xclose (sock);
1232 if (!obj->config.servers[server_index].disable_tcp)
1234 int sock = xsocket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1235 xconnect (sock,
1236 (struct sockaddr *) &obj->servers[server_index].address,
1237 sizeof (obj->servers[server_index].address));
1238 xclose (sock);
1242 if (obj->config.single_thread_udp)
1243 xpthread_join (obj->thread_udp_single);
1245 /* Wait for the server threads to terminate. */
1246 for (int server_index = 0; server_index < obj->config.nscount;
1247 ++server_index)
1249 if (!obj->config.servers[server_index].disable_udp)
1251 if (!obj->config.single_thread_udp)
1252 xpthread_join (obj->servers[server_index].thread_udp);
1253 xclose (obj->servers[server_index].socket_udp);
1255 if (!obj->config.servers[server_index].disable_tcp)
1257 xpthread_join (obj->servers[server_index].thread_tcp);
1258 xclose (obj->servers[server_index].socket_tcp);
1262 free (obj);