1/* Copyright (C) 2016 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
8
9 The GNU C Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public
15 License along with the GNU C Library; if not, see
16 <http://www.gnu.org/licenses/>. */
17
18/*
19 * Copyright (c) 1985, 1989, 1993
20 * The Regents of the University of California. All rights reserved.
21 *
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
24 * are met:
25 * 1. Redistributions of source code must retain the above copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 4. Neither the name of the University nor the names of its contributors
31 * may be used to endorse or promote products derived from this software
32 * without specific prior written permission.
33 *
34 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
35 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
36 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
37 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
38 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
39 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
40 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
41 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
42 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
43 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
44 * SUCH DAMAGE.
45 */
46
47/*
48 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
49 *
50 * Permission to use, copy, modify, and distribute this software for any
51 * purpose with or without fee is hereby granted, provided that the above
52 * copyright notice and this permission notice appear in all copies, and that
53 * the name of Digital Equipment Corporation not be used in advertising or
54 * publicity pertaining to distribution of the document or software without
55 * specific, written prior permission.
56 *
57 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
58 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
59 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
60 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
61 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
62 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
63 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
64 * SOFTWARE.
65 */
66
67/*
68 * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
69 *
70 * Permission to use, copy, modify, and distribute this software for any
71 * purpose with or without fee is hereby granted, provided that the above
72 * copyright notice and this permission notice appear in all copies.
73 *
74 * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
75 * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
76 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
77 * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
78 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
79 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
80 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
81 * SOFTWARE.
82 */
83
84#if defined(LIBC_SCCS) && !defined(lint)
85static const char sccsid[] = "@(#)res_send.c 8.1 (Berkeley) 6/4/93";
86static const char rcsid[] = "$BINDId: res_send.c,v 8.38 2000/03/30 20:16:51 vixie Exp $";
87#endif /* LIBC_SCCS and not lint */
88
89/*
90 * Send query to name server and wait for reply.
91 */
92
93#include <assert.h>
94#include <sys/types.h>
95#include <sys/param.h>
96#include <sys/time.h>
97#include <sys/socket.h>
98#include <sys/uio.h>
99#include <sys/poll.h>
100
101#include <netinet/in.h>
102#include <arpa/nameser.h>
103#include <arpa/inet.h>
104#include <sys/ioctl.h>
105
106#include <errno.h>
107#include <fcntl.h>
108#include <netdb.h>
109#include <resolv.h>
110#include <signal.h>
111#include <stdio.h>
112#include <stdlib.h>
113#include <string.h>
114#include <unistd.h>
115#include <kernel-features.h>
116#include <libc-internal.h>
117
118#if PACKETSZ > 65536
119#define MAXPACKET PACKETSZ
120#else
121#define MAXPACKET 65536
122#endif
123
124/* From ev_streams.c. */
125
126static inline void
127__attribute ((always_inline))
128evConsIovec(void *buf, size_t cnt, struct iovec *vec) {
129 memset(vec, 0xf5, sizeof (*vec));
130 vec->iov_base = buf;
131 vec->iov_len = cnt;
132}
133
134/* From ev_timers.c. */
135
136#define BILLION 1000000000
137
138static inline void
139evConsTime(struct timespec *res, time_t sec, long nsec) {
140 res->tv_sec = sec;
141 res->tv_nsec = nsec;
142}
143
144static inline void
145evAddTime(struct timespec *res, const struct timespec *addend1,
146 const struct timespec *addend2) {
147 res->tv_sec = addend1->tv_sec + addend2->tv_sec;
148 res->tv_nsec = addend1->tv_nsec + addend2->tv_nsec;
149 if (res->tv_nsec >= BILLION) {
150 res->tv_sec++;
151 res->tv_nsec -= BILLION;
152 }
153}
154
155static inline void
156evSubTime(struct timespec *res, const struct timespec *minuend,
157 const struct timespec *subtrahend) {
158 res->tv_sec = minuend->tv_sec - subtrahend->tv_sec;
159 if (minuend->tv_nsec >= subtrahend->tv_nsec)
160 res->tv_nsec = minuend->tv_nsec - subtrahend->tv_nsec;
161 else {
162 res->tv_nsec = (BILLION
163 - subtrahend->tv_nsec + minuend->tv_nsec);
164 res->tv_sec--;
165 }
166}
167
168static int
169evCmpTime(struct timespec a, struct timespec b) {
170 long x = a.tv_sec - b.tv_sec;
171
172 if (x == 0L)
173 x = a.tv_nsec - b.tv_nsec;
174 return (x < 0L ? (-1) : x > 0L ? (1) : (0));
175}
176
177static void
178evNowTime(struct timespec *res) {
179 struct timeval now;
180
181 if (gettimeofday(&now, NULL) < 0)
182 evConsTime(res, 0, 0);
183 else
184 TIMEVAL_TO_TIMESPEC (&now, res);
185}
186
187
188/* Options. Leave them on. */
189/* #undef DEBUG */
190#include "res_debug.h"
191
192#define EXT(res) ((res)->_u._ext)
193
194/* Forward. */
195
196static struct sockaddr *get_nsaddr (res_state, int);
197static int send_vc(res_state, const u_char *, int,
198 const u_char *, int,
199 u_char **, int *, int *, int, u_char **,
200 u_char **, int *, int *, int *);
201static int send_dg(res_state, const u_char *, int,
202 const u_char *, int,
203 u_char **, int *, int *, int,
204 int *, int *, u_char **,
205 u_char **, int *, int *, int *);
206#ifdef DEBUG
207static void Aerror(const res_state, FILE *, const char *, int,
208 const struct sockaddr *);
209static void Perror(const res_state, FILE *, const char *, int);
210#endif
211static int sock_eq(struct sockaddr_in6 *, struct sockaddr_in6 *);
212
213/* Public. */
214
215/* int
216 * res_isourserver(ina)
217 * looks up "ina" in _res.ns_addr_list[]
218 * returns:
219 * 0 : not found
220 * >0 : found
221 * author:
222 * paul vixie, 29may94
223 */
224int
225res_ourserver_p(const res_state statp, const struct sockaddr_in6 *inp)
226{
227 int ns;
228
229 if (inp->sin6_family == AF_INET) {
230 struct sockaddr_in *in4p = (struct sockaddr_in *) inp;
231 in_port_t port = in4p->sin_port;
232 in_addr_t addr = in4p->sin_addr.s_addr;
233
234 for (ns = 0; ns < statp->nscount; ns++) {
235 const struct sockaddr_in *srv =
236 (struct sockaddr_in *) get_nsaddr (statp, ns);
237
238 if ((srv->sin_family == AF_INET) &&
239 (srv->sin_port == port) &&
240 (srv->sin_addr.s_addr == INADDR_ANY ||
241 srv->sin_addr.s_addr == addr))
242 return (1);
243 }
244 } else if (inp->sin6_family == AF_INET6) {
245 for (ns = 0; ns < statp->nscount; ns++) {
246 const struct sockaddr_in6 *srv
247 = (struct sockaddr_in6 *) get_nsaddr (statp, ns);
248 if ((srv->sin6_family == AF_INET6) &&
249 (srv->sin6_port == inp->sin6_port) &&
250 !(memcmp(&srv->sin6_addr, &in6addr_any,
251 sizeof (struct in6_addr)) &&
252 memcmp(&srv->sin6_addr, &inp->sin6_addr,
253 sizeof (struct in6_addr))))
254 return (1);
255 }
256 }
257 return (0);
258}
259
260/* int
261 * res_nameinquery(name, type, class, buf, eom)
262 * look for (name,type,class) in the query section of packet (buf,eom)
263 * requires:
264 * buf + HFIXEDSZ <= eom
265 * returns:
266 * -1 : format error
267 * 0 : not found
268 * >0 : found
269 * author:
270 * paul vixie, 29may94
271 */
272int
273res_nameinquery(const char *name, int type, int class,
274 const u_char *buf, const u_char *eom)
275{
276 const u_char *cp = buf + HFIXEDSZ;
277 int qdcount = ntohs(((HEADER*)buf)->qdcount);
278
279 while (qdcount-- > 0) {
280 char tname[MAXDNAME+1];
281 int n, ttype, tclass;
282
283 n = dn_expand(buf, eom, cp, tname, sizeof tname);
284 if (n < 0)
285 return (-1);
286 cp += n;
287 if (cp + 2 * INT16SZ > eom)
288 return (-1);
289 NS_GET16(ttype, cp);
290 NS_GET16(tclass, cp);
291 if (ttype == type && tclass == class &&
292 ns_samename(tname, name) == 1)
293 return (1);
294 }
295 return (0);
296}
297libresolv_hidden_def (res_nameinquery)
298
299/* int
300 * res_queriesmatch(buf1, eom1, buf2, eom2)
301 * is there a 1:1 mapping of (name,type,class)
302 * in (buf1,eom1) and (buf2,eom2)?
303 * returns:
304 * -1 : format error
305 * 0 : not a 1:1 mapping
306 * >0 : is a 1:1 mapping
307 * author:
308 * paul vixie, 29may94
309 */
310int
311res_queriesmatch(const u_char *buf1, const u_char *eom1,
312 const u_char *buf2, const u_char *eom2)
313{
314 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2)
315 return (-1);
316
317 /*
318 * Only header section present in replies to
319 * dynamic update packets.
320 */
321 if ((((HEADER *)buf1)->opcode == ns_o_update) &&
322 (((HEADER *)buf2)->opcode == ns_o_update))
323 return (1);
324
325 /* Note that we initially do not convert QDCOUNT to the host byte
326 order. We can compare it with the second buffer's QDCOUNT
327 value without doing this. */
328 int qdcount = ((HEADER*)buf1)->qdcount;
329 if (qdcount != ((HEADER*)buf2)->qdcount)
330 return (0);
331
332 qdcount = htons (qdcount);
333 const u_char *cp = buf1 + HFIXEDSZ;
334
335 while (qdcount-- > 0) {
336 char tname[MAXDNAME+1];
337 int n, ttype, tclass;
338
339 n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
340 if (n < 0)
341 return (-1);
342 cp += n;
343 if (cp + 2 * INT16SZ > eom1)
344 return (-1);
345 NS_GET16(ttype, cp);
346 NS_GET16(tclass, cp);
347 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2))
348 return (0);
349 }
350 return (1);
351}
352libresolv_hidden_def (res_queriesmatch)
353
354int
355__libc_res_nsend(res_state statp, const u_char *buf, int buflen,
356 const u_char *buf2, int buflen2,
357 u_char *ans, int anssiz, u_char **ansp, u_char **ansp2,
358 int *nansp2, int *resplen2, int *ansp2_malloced)
359{
360 int gotsomewhere, terrno, try, v_circuit, resplen, ns, n;
361
362 if (statp->nscount == 0) {
363 __set_errno (ESRCH);
364 return (-1);
365 }
366
367 if (anssiz < (buf2 == NULL ? 1 : 2) * HFIXEDSZ) {
368 __set_errno (EINVAL);
369 return (-1);
370 }
371
372#ifdef USE_HOOKS
373 if (__glibc_unlikely (statp->qhook || statp->rhook)) {
374 if (anssiz < MAXPACKET && ansp) {
375 /* Always allocate MAXPACKET, callers expect
376 this specific size. */
377 u_char *buf = malloc (MAXPACKET);
378 if (buf == NULL)
379 return (-1);
380 memcpy (buf, ans, HFIXEDSZ);
381 *ansp = buf;
382 ans = buf;
383 anssiz = MAXPACKET;
384 }
385 }
386#endif
387
388 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_QUERY),
389 (stdout, ";; res_send()\n"), buf, buflen);
390 v_circuit = ((statp->options & RES_USEVC)
391 || buflen > PACKETSZ
392 || buflen2 > PACKETSZ);
393 gotsomewhere = 0;
394 terrno = ETIMEDOUT;
395
396 /*
397 * If the ns_addr_list in the resolver context has changed, then
398 * invalidate our cached copy and the associated timing data.
399 */
400 if (EXT(statp).nscount != 0) {
401 int needclose = 0;
402
403 if (EXT(statp).nscount != statp->nscount)
404 needclose++;
405 else
406 for (ns = 0; ns < statp->nscount; ns++) {
407 if (statp->nsaddr_list[ns].sin_family != 0
408 && !sock_eq((struct sockaddr_in6 *)
409 &statp->nsaddr_list[ns],
410 EXT(statp).nsaddrs[ns]))
411 {
412 needclose++;
413 break;
414 }
415 }
416 if (needclose) {
417 __res_iclose(statp, false);
418 EXT(statp).nscount = 0;
419 }
420 }
421
422 /*
423 * Maybe initialize our private copy of the ns_addr_list.
424 */
425 if (EXT(statp).nscount == 0) {
426 for (ns = 0; ns < statp->nscount; ns++) {
427 EXT(statp).nssocks[ns] = -1;
428 if (statp->nsaddr_list[ns].sin_family == 0)
429 continue;
430 if (EXT(statp).nsaddrs[ns] == NULL)
431 EXT(statp).nsaddrs[ns] =
432 malloc(sizeof (struct sockaddr_in6));
433 if (EXT(statp).nsaddrs[ns] != NULL)
434 memset (mempcpy(EXT(statp).nsaddrs[ns],
435 &statp->nsaddr_list[ns],
436 sizeof (struct sockaddr_in)),
437 '\0',
438 sizeof (struct sockaddr_in6)
439 - sizeof (struct sockaddr_in));
440 }
441 EXT(statp).nscount = statp->nscount;
442 }
443
444 /*
445 * Some resolvers want to even out the load on their nameservers.
446 * Note that RES_BLAST overrides RES_ROTATE.
447 */
448 if (__builtin_expect ((statp->options & RES_ROTATE) != 0, 0) &&
449 (statp->options & RES_BLAST) == 0) {
450 struct sockaddr_in ina;
451 struct sockaddr_in6 *inp;
452 int lastns = statp->nscount - 1;
453 int fd;
454
455 inp = EXT(statp).nsaddrs[0];
456 ina = statp->nsaddr_list[0];
457 fd = EXT(statp).nssocks[0];
458 for (ns = 0; ns < lastns; ns++) {
459 EXT(statp).nsaddrs[ns] = EXT(statp).nsaddrs[ns + 1];
460 statp->nsaddr_list[ns] = statp->nsaddr_list[ns + 1];
461 EXT(statp).nssocks[ns] = EXT(statp).nssocks[ns + 1];
462 }
463 EXT(statp).nsaddrs[lastns] = inp;
464 statp->nsaddr_list[lastns] = ina;
465 EXT(statp).nssocks[lastns] = fd;
466 }
467
468 /*
469 * Send request, RETRY times, or until successful.
470 */
471 for (try = 0; try < statp->retry; try++) {
472 for (ns = 0; ns < statp->nscount; ns++)
473 {
474#ifdef DEBUG
475 char tmpbuf[40];
476#endif
477#if defined USE_HOOKS || defined DEBUG
478 struct sockaddr *nsap = get_nsaddr (statp, ns);
479#endif
480
481 same_ns:
482#ifdef USE_HOOKS
483 if (__glibc_unlikely (statp->qhook != NULL)) {
484 int done = 0, loops = 0;
485
486 do {
487 res_sendhookact act;
488
489 struct sockaddr_in *nsap4;
490 nsap4 = (struct sockaddr_in *) nsap;
491 act = (*statp->qhook)(&nsap4, &buf, &buflen,
492 ans, anssiz, &resplen);
493 nsap = (struct sockaddr_in6 *) nsap4;
494 switch (act) {
495 case res_goahead:
496 done = 1;
497 break;
498 case res_nextns:
499 __res_iclose(statp, false);
500 goto next_ns;
501 case res_done:
502 return (resplen);
503 case res_modified:
504 /* give the hook another try */
505 if (++loops < 42) /*doug adams*/
506 break;
507 /*FALLTHROUGH*/
508 case res_error:
509 /*FALLTHROUGH*/
510 default:
511 return (-1);
512 }
513 } while (!done);
514 }
515#endif
516
517 Dprint(statp->options & RES_DEBUG,
518 (stdout, ";; Querying server (# %d) address = %s\n",
519 ns + 1, inet_ntop(nsap->sa_family,
520 (nsap->sa_family == AF_INET6
521 ? (void *) &((struct sockaddr_in6 *) nsap)->sin6_addr
522 : (void *) &((struct sockaddr_in *) nsap)->sin_addr),
523 tmpbuf, sizeof (tmpbuf))));
524
525 if (__glibc_unlikely (v_circuit)) {
526 /* Use VC; at most one attempt per server. */
527 try = statp->retry;
528 n = send_vc(statp, buf, buflen, buf2, buflen2,
529 &ans, &anssiz, &terrno,
530 ns, ansp, ansp2, nansp2, resplen2,
531 ansp2_malloced);
532 if (n < 0)
533 return (-1);
534 if (n == 0 && (buf2 == NULL || *resplen2 == 0))
535 goto next_ns;
536 } else {
537 /* Use datagrams. */
538 n = send_dg(statp, buf, buflen, buf2, buflen2,
539 &ans, &anssiz, &terrno,
540 ns, &v_circuit, &gotsomewhere, ansp,
541 ansp2, nansp2, resplen2, ansp2_malloced);
542 if (n < 0)
543 return (-1);
544 if (n == 0 && (buf2 == NULL || *resplen2 == 0))
545 goto next_ns;
546 if (v_circuit)
547 // XXX Check whether both requests failed or
548 // XXX whether one has been answered successfully
549 goto same_ns;
550 }
551
552 resplen = n;
553
554 Dprint((statp->options & RES_DEBUG) ||
555 ((statp->pfcode & RES_PRF_REPLY) &&
556 (statp->pfcode & RES_PRF_HEAD1)),
557 (stdout, ";; got answer:\n"));
558
559 DprintQ((statp->options & RES_DEBUG) ||
560 (statp->pfcode & RES_PRF_REPLY),
561 (stdout, "%s", ""),
562 ans, (resplen > anssiz) ? anssiz : resplen);
563 if (buf2 != NULL) {
564 DprintQ((statp->options & RES_DEBUG) ||
565 (statp->pfcode & RES_PRF_REPLY),
566 (stdout, "%s", ""),
567 *ansp2, (*resplen2 > *nansp2) ? *nansp2 : *resplen2);
568 }
569
570 /*
571 * If we have temporarily opened a virtual circuit,
572 * or if we haven't been asked to keep a socket open,
573 * close the socket.
574 */
575 if ((v_circuit && (statp->options & RES_USEVC) == 0) ||
576 (statp->options & RES_STAYOPEN) == 0) {
577 __res_iclose(statp, false);
578 }
579#ifdef USE_HOOKS
580 if (__glibc_unlikely (statp->rhook)) {
581 int done = 0, loops = 0;
582
583 do {
584 res_sendhookact act;
585
586 act = (*statp->rhook)((struct sockaddr_in *)
587 nsap, buf, buflen,
588 ans, anssiz, &resplen);
589 switch (act) {
590 case res_goahead:
591 case res_done:
592 done = 1;
593 break;
594 case res_nextns:
595 __res_iclose(statp, false);
596 goto next_ns;
597 case res_modified:
598 /* give the hook another try */
599 if (++loops < 42) /*doug adams*/
600 break;
601 /*FALLTHROUGH*/
602 case res_error:
603 /*FALLTHROUGH*/
604 default:
605 return (-1);
606 }
607 } while (!done);
608
609 }
610#endif
611 return (resplen);
612 next_ns: ;
613 } /*foreach ns*/
614 } /*foreach retry*/
615 __res_iclose(statp, false);
616 if (!v_circuit) {
617 if (!gotsomewhere)
618 __set_errno (ECONNREFUSED); /* no nameservers found */
619 else
620 __set_errno (ETIMEDOUT); /* no answer obtained */
621 } else
622 __set_errno (terrno);
623 return (-1);
624}
625
626int
627res_nsend(res_state statp,
628 const u_char *buf, int buflen, u_char *ans, int anssiz)
629{
630 return __libc_res_nsend(statp, buf, buflen, NULL, 0, ans, anssiz,
631 NULL, NULL, NULL, NULL, NULL);
632}
633libresolv_hidden_def (res_nsend)
634
635/* Private */
636
637static struct sockaddr *
638get_nsaddr (res_state statp, int n)
639{
640
641 if (statp->nsaddr_list[n].sin_family == 0 && EXT(statp).nsaddrs[n] != NULL)
642 /* EXT(statp).nsaddrs[n] holds an address that is larger than
643 struct sockaddr, and user code did not update
644 statp->nsaddr_list[n]. */
645 return (struct sockaddr *) EXT(statp).nsaddrs[n];
646 else
647 /* User code updated statp->nsaddr_list[n], or statp->nsaddr_list[n]
648 has the same content as EXT(statp).nsaddrs[n]. */
649 return (struct sockaddr *) (void *) &statp->nsaddr_list[n];
650}
651
652/* Close the resolver structure, assign zero to *RESPLEN2 if RESPLEN2
653 is not NULL, and return zero. */
654static int
655__attribute__ ((warn_unused_result))
656close_and_return_error (res_state statp, int *resplen2)
657{
658 __res_iclose(statp, false);
659 if (resplen2 != NULL)
660 *resplen2 = 0;
661 return 0;
662}
663
664/* The send_vc function is responsible for sending a DNS query over TCP
665 to the nameserver numbered NS from the res_state STATP i.e.
666 EXT(statp).nssocks[ns]. The function supports sending both IPv4 and
667 IPv6 queries at the same serially on the same socket.
668
669 Please note that for TCP there is no way to disable sending both
670 queries, unlike UDP, which honours RES_SNGLKUP and RES_SNGLKUPREOP
671 and sends the queries serially and waits for the result after each
672 sent query. This implemetnation should be corrected to honour these
673 options.
674
675 Please also note that for TCP we send both queries over the same
676 socket one after another. This technically violates best practice
677 since the server is allowed to read the first query, respond, and
678 then close the socket (to service another client). If the server
679 does this, then the remaining second query in the socket data buffer
680 will cause the server to send the client an RST which will arrive
681 asynchronously and the client's OS will likely tear down the socket
682 receive buffer resulting in a potentially short read and lost
683 response data. This will force the client to retry the query again,
684 and this process may repeat until all servers and connection resets
685 are exhausted and then the query will fail. It's not known if this
686 happens with any frequency in real DNS server implementations. This
687 implementation should be corrected to use two sockets by default for
688 parallel queries.
689
690 The query stored in BUF of BUFLEN length is sent first followed by
691 the query stored in BUF2 of BUFLEN2 length. Queries are sent
692 serially on the same socket.
693
694 Answers to the query are stored firstly in *ANSP up to a max of
695 *ANSSIZP bytes. If more than *ANSSIZP bytes are needed and ANSCP
696 is non-NULL (to indicate that modifying the answer buffer is allowed)
697 then malloc is used to allocate a new response buffer and ANSCP and
698 ANSP will both point to the new buffer. If more than *ANSSIZP bytes
699 are needed but ANSCP is NULL, then as much of the response as
700 possible is read into the buffer, but the results will be truncated.
701 When truncation happens because of a small answer buffer the DNS
702 packets header field TC will bet set to 1, indicating a truncated
703 message and the rest of the socket data will be read and discarded.
704
705 Answers to the query are stored secondly in *ANSP2 up to a max of
706 *ANSSIZP2 bytes, with the actual response length stored in
707 *RESPLEN2. If more than *ANSSIZP bytes are needed and ANSP2
708 is non-NULL (required for a second query) then malloc is used to
709 allocate a new response buffer, *ANSSIZP2 is set to the new buffer
710 size and *ANSP2_MALLOCED is set to 1.
711
712 The ANSP2_MALLOCED argument will eventually be removed as the
713 change in buffer pointer can be used to detect the buffer has
714 changed and that the caller should use free on the new buffer.
715
716 Note that the answers may arrive in any order from the server and
717 therefore the first and second answer buffers may not correspond to
718 the first and second queries.
719
720 It is not supported to call this function with a non-NULL ANSP2
721 but a NULL ANSCP. Put another way, you can call send_vc with a
722 single unmodifiable buffer or two modifiable buffers, but no other
723 combination is supported.
724
725 It is the caller's responsibility to free the malloc allocated
726 buffers by detecting that the pointers have changed from their
727 original values i.e. *ANSCP or *ANSP2 has changed.
728
729 If errors are encountered then *TERRNO is set to an appropriate
730 errno value and a zero result is returned for a recoverable error,
731 and a less-than zero result is returned for a non-recoverable error.
732
733 If no errors are encountered then *TERRNO is left unmodified and
734 a the length of the first response in bytes is returned. */
735static int
736send_vc(res_state statp,
737 const u_char *buf, int buflen, const u_char *buf2, int buflen2,
738 u_char **ansp, int *anssizp,
739 int *terrno, int ns, u_char **anscp, u_char **ansp2, int *anssizp2,
740 int *resplen2, int *ansp2_malloced)
741{
742 const HEADER *hp = (HEADER *) buf;
743 const HEADER *hp2 = (HEADER *) buf2;
744 HEADER *anhp = (HEADER *) *ansp;
745 struct sockaddr *nsap = get_nsaddr (statp, ns);
746 int truncating, connreset, n;
747 /* On some architectures compiler might emit a warning indicating
748 'resplen' may be used uninitialized. However if buf2 == NULL
749 then this code won't be executed; if buf2 != NULL, then first
750 time round the loop recvresp1 and recvresp2 will be 0 so this
751 code won't be executed but "thisresplenp = &resplen;" followed
752 by "*thisresplenp = rlen;" will be executed so that subsequent
753 times round the loop resplen has been initialized. So this is
754 a false-positive.
755 */
756 DIAG_PUSH_NEEDS_COMMENT;
757 DIAG_IGNORE_NEEDS_COMMENT (5, "-Wmaybe-uninitialized");
758 int resplen;
759 DIAG_POP_NEEDS_COMMENT;
760 struct iovec iov[4];
761 u_short len;
762 u_short len2;
763 u_char *cp;
764
765 connreset = 0;
766 same_ns:
767 truncating = 0;
768
769 /* Are we still talking to whom we want to talk to? */
770 if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
771 struct sockaddr_in6 peer;
772 socklen_t size = sizeof peer;
773
774 if (getpeername(statp->_vcsock,
775 (struct sockaddr *)&peer, &size) < 0 ||
776 !sock_eq(&peer, (struct sockaddr_in6 *) nsap)) {
777 __res_iclose(statp, false);
778 statp->_flags &= ~RES_F_VC;
779 }
780 }
781
782 if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
783 if (statp->_vcsock >= 0)
784 __res_iclose(statp, false);
785
786 statp->_vcsock = socket(nsap->sa_family, SOCK_STREAM, 0);
787 if (statp->_vcsock < 0) {
788 *terrno = errno;
789 Perror(statp, stderr, "socket(vc)", errno);
790 if (resplen2 != NULL)
791 *resplen2 = 0;
792 return (-1);
793 }
794 __set_errno (0);
795 if (connect(statp->_vcsock, nsap,
796 nsap->sa_family == AF_INET
797 ? sizeof (struct sockaddr_in)
798 : sizeof (struct sockaddr_in6)) < 0) {
799 *terrno = errno;
800 Aerror(statp, stderr, "connect/vc", errno, nsap);
801 return close_and_return_error (statp, resplen2);
802 }
803 statp->_flags |= RES_F_VC;
804 }
805
806 /*
807 * Send length & message
808 */
809 len = htons ((u_short) buflen);
810 evConsIovec(&len, INT16SZ, &iov[0]);
811 evConsIovec((void*)buf, buflen, &iov[1]);
812 int niov = 2;
813 ssize_t explen = INT16SZ + buflen;
814 if (buf2 != NULL) {
815 len2 = htons ((u_short) buflen2);
816 evConsIovec(&len2, INT16SZ, &iov[2]);
817 evConsIovec((void*)buf2, buflen2, &iov[3]);
818 niov = 4;
819 explen += INT16SZ + buflen2;
820 }
821 if (TEMP_FAILURE_RETRY (writev(statp->_vcsock, iov, niov)) != explen) {
822 *terrno = errno;
823 Perror(statp, stderr, "write failed", errno);
824 return close_and_return_error (statp, resplen2);
825 }
826 /*
827 * Receive length & response
828 */
829 int recvresp1 = 0;
830 /* Skip the second response if there is no second query.
831 To do that we mark the second response as received. */
832 int recvresp2 = buf2 == NULL;
833 uint16_t rlen16;
834 read_len:
835 cp = (u_char *)&rlen16;
836 len = sizeof(rlen16);
837 while ((n = TEMP_FAILURE_RETRY (read(statp->_vcsock, cp,
838 (int)len))) > 0) {
839 cp += n;
840 if ((len -= n) <= 0)
841 break;
842 }
843 if (n <= 0) {
844 *terrno = errno;
845 Perror(statp, stderr, "read failed", errno);
846 /*
847 * A long running process might get its TCP
848 * connection reset if the remote server was
849 * restarted. Requery the server instead of
850 * trying a new one. When there is only one
851 * server, this means that a query might work
852 * instead of failing. We only allow one reset
853 * per query to prevent looping.
854 */
855 if (*terrno == ECONNRESET && !connreset)
856 {
857 __res_iclose (statp, false);
858 connreset = 1;
859 goto same_ns;
860 }
861 return close_and_return_error (statp, resplen2);
862 }
863 int rlen = ntohs (rlen16);
864
865 int *thisanssizp;
866 u_char **thisansp;
867 int *thisresplenp;
868 if ((recvresp1 | recvresp2) == 0 || buf2 == NULL) {
869 /* We have not received any responses
870 yet or we only have one response to
871 receive. */
872 thisanssizp = anssizp;
873 thisansp = anscp ?: ansp;
874 assert (anscp != NULL || ansp2 == NULL);
875 thisresplenp = &resplen;
876 } else {
877 thisanssizp = anssizp2;
878 thisansp = ansp2;
879 thisresplenp = resplen2;
880 }
881 anhp = (HEADER *) *thisansp;
882
883 *thisresplenp = rlen;
884 /* Is the answer buffer too small? */
885 if (*thisanssizp < rlen) {
886 /* If the current buffer is not the the static
887 user-supplied buffer then we can reallocate
888 it. */
889 if (thisansp != NULL && thisansp != ansp) {
890 /* Always allocate MAXPACKET, callers expect
891 this specific size. */
892 u_char *newp = malloc (MAXPACKET);
893 if (newp == NULL)
894 {
895 *terrno = ENOMEM;
896 return close_and_return_error (statp, resplen2);
897 }
898 *thisanssizp = MAXPACKET;
899 *thisansp = newp;
900 if (thisansp == ansp2)
901 *ansp2_malloced = 1;
902 anhp = (HEADER *) newp;
903 /* A uint16_t can't be larger than MAXPACKET
904 thus it's safe to allocate MAXPACKET but
905 read RLEN bytes instead. */
906 len = rlen;
907 } else {
908 Dprint(statp->options & RES_DEBUG,
909 (stdout, ";; response truncated\n")
910 );
911 truncating = 1;
912 len = *thisanssizp;
913 }
914 } else
915 len = rlen;
916
917 if (__glibc_unlikely (len < HFIXEDSZ)) {
918 /*
919 * Undersized message.
920 */
921 Dprint(statp->options & RES_DEBUG,
922 (stdout, ";; undersized: %d\n", len));
923 *terrno = EMSGSIZE;
924 return close_and_return_error (statp, resplen2);
925 }
926
927 cp = *thisansp;
928 while (len != 0 && (n = read(statp->_vcsock, (char *)cp, (int)len)) > 0){
929 cp += n;
930 len -= n;
931 }
932 if (__glibc_unlikely (n <= 0)) {
933 *terrno = errno;
934 Perror(statp, stderr, "read(vc)", errno);
935 return close_and_return_error (statp, resplen2);
936 }
937 if (__glibc_unlikely (truncating)) {
938 /*
939 * Flush rest of answer so connection stays in synch.
940 */
941 anhp->tc = 1;
942 len = rlen - *thisanssizp;
943 while (len != 0) {
944 char junk[PACKETSZ];
945
946 n = read(statp->_vcsock, junk,
947 (len > sizeof junk) ? sizeof junk : len);
948 if (n > 0)
949 len -= n;
950 else
951 break;
952 }
953 }
954 /*
955 * If the calling application has bailed out of
956 * a previous call and failed to arrange to have
957 * the circuit closed or the server has got
958 * itself confused, then drop the packet and
959 * wait for the correct one.
960 */
961 if ((recvresp1 || hp->id != anhp->id)
962 && (recvresp2 || hp2->id != anhp->id)) {
963 DprintQ((statp->options & RES_DEBUG) ||
964 (statp->pfcode & RES_PRF_REPLY),
965 (stdout, ";; old answer (unexpected):\n"),
966 *thisansp,
967 (rlen > *thisanssizp) ? *thisanssizp: rlen);
968 goto read_len;
969 }
970
971 /* Mark which reply we received. */
972 if (recvresp1 == 0 && hp->id == anhp->id)
973 recvresp1 = 1;
974 else
975 recvresp2 = 1;
976 /* Repeat waiting if we have a second answer to arrive. */
977 if ((recvresp1 & recvresp2) == 0)
978 goto read_len;
979
980 /*
981 * All is well, or the error is fatal. Signal that the
982 * next nameserver ought not be tried.
983 */
984 return resplen;
985}
986
987static int
988reopen (res_state statp, int *terrno, int ns)
989{
990 if (EXT(statp).nssocks[ns] == -1) {
991 struct sockaddr *nsap = get_nsaddr (statp, ns);
992 socklen_t slen;
993
994 /* only try IPv6 if IPv6 NS and if not failed before */
995 if (nsap->sa_family == AF_INET6 && !statp->ipv6_unavail) {
996 EXT(statp).nssocks[ns]
997 = socket(PF_INET6, SOCK_DGRAM|SOCK_NONBLOCK, 0);
998 if (EXT(statp).nssocks[ns] < 0)
999 statp->ipv6_unavail = errno == EAFNOSUPPORT;
1000 slen = sizeof (struct sockaddr_in6);
1001 } else if (nsap->sa_family == AF_INET) {
1002 EXT(statp).nssocks[ns]
1003 = socket(PF_INET, SOCK_DGRAM|SOCK_NONBLOCK, 0);
1004 slen = sizeof (struct sockaddr_in);
1005 }
1006 if (EXT(statp).nssocks[ns] < 0) {
1007 *terrno = errno;
1008 Perror(statp, stderr, "socket(dg)", errno);
1009 return (-1);
1010 }
1011
1012 /*
1013 * On a 4.3BSD+ machine (client and server,
1014 * actually), sending to a nameserver datagram
1015 * port with no nameserver will cause an
1016 * ICMP port unreachable message to be returned.
1017 * If our datagram socket is "connected" to the
1018 * server, we get an ECONNREFUSED error on the next
1019 * socket operation, and select returns if the
1020 * error message is received. We can thus detect
1021 * the absence of a nameserver without timing out.
1022 */
1023 if (connect(EXT(statp).nssocks[ns], nsap, slen) < 0) {
1024 Aerror(statp, stderr, "connect(dg)", errno, nsap);
1025 __res_iclose(statp, false);
1026 return (0);
1027 }
1028 }
1029
1030 return 1;
1031}
1032
1033/* The send_dg function is responsible for sending a DNS query over UDP
1034 to the nameserver numbered NS from the res_state STATP i.e.
1035 EXT(statp).nssocks[ns]. The function supports IPv4 and IPv6 queries
1036 along with the ability to send the query in parallel for both stacks
1037 (default) or serially (RES_SINGLKUP). It also supports serial lookup
1038 with a close and reopen of the socket used to talk to the server
1039 (RES_SNGLKUPREOP) to work around broken name servers.
1040
1041 The query stored in BUF of BUFLEN length is sent first followed by
1042 the query stored in BUF2 of BUFLEN2 length. Queries are sent
1043 in parallel (default) or serially (RES_SINGLKUP or RES_SNGLKUPREOP).
1044
1045 Answers to the query are stored firstly in *ANSP up to a max of
1046 *ANSSIZP bytes. If more than *ANSSIZP bytes are needed and ANSCP
1047 is non-NULL (to indicate that modifying the answer buffer is allowed)
1048 then malloc is used to allocate a new response buffer and ANSCP and
1049 ANSP will both point to the new buffer. If more than *ANSSIZP bytes
1050 are needed but ANSCP is NULL, then as much of the response as
1051 possible is read into the buffer, but the results will be truncated.
1052 When truncation happens because of a small answer buffer the DNS
1053 packets header field TC will bet set to 1, indicating a truncated
1054 message, while the rest of the UDP packet is discarded.
1055
1056 Answers to the query are stored secondly in *ANSP2 up to a max of
1057 *ANSSIZP2 bytes, with the actual response length stored in
1058 *RESPLEN2. If more than *ANSSIZP bytes are needed and ANSP2
1059 is non-NULL (required for a second query) then malloc is used to
1060 allocate a new response buffer, *ANSSIZP2 is set to the new buffer
1061 size and *ANSP2_MALLOCED is set to 1.
1062
1063 The ANSP2_MALLOCED argument will eventually be removed as the
1064 change in buffer pointer can be used to detect the buffer has
1065 changed and that the caller should use free on the new buffer.
1066
1067 Note that the answers may arrive in any order from the server and
1068 therefore the first and second answer buffers may not correspond to
1069 the first and second queries.
1070
1071 It is not supported to call this function with a non-NULL ANSP2
1072 but a NULL ANSCP. Put another way, you can call send_vc with a
1073 single unmodifiable buffer or two modifiable buffers, but no other
1074 combination is supported.
1075
1076 It is the caller's responsibility to free the malloc allocated
1077 buffers by detecting that the pointers have changed from their
1078 original values i.e. *ANSCP or *ANSP2 has changed.
1079
1080 If an answer is truncated because of UDP datagram DNS limits then
1081 *V_CIRCUIT is set to 1 and the return value non-zero to indicate to
1082 the caller to retry with TCP. The value *GOTSOMEWHERE is set to 1
1083 if any progress was made reading a response from the nameserver and
1084 is used by the caller to distinguish between ECONNREFUSED and
1085 ETIMEDOUT (the latter if *GOTSOMEWHERE is 1).
1086
1087 If errors are encountered then *TERRNO is set to an appropriate
1088 errno value and a zero result is returned for a recoverable error,
1089 and a less-than zero result is returned for a non-recoverable error.
1090
1091 If no errors are encountered then *TERRNO is left unmodified and
1092 a the length of the first response in bytes is returned. */
1093static int
1094send_dg(res_state statp,
1095 const u_char *buf, int buflen, const u_char *buf2, int buflen2,
1096 u_char **ansp, int *anssizp,
1097 int *terrno, int ns, int *v_circuit, int *gotsomewhere, u_char **anscp,
1098 u_char **ansp2, int *anssizp2, int *resplen2, int *ansp2_malloced)
1099{
1100 const HEADER *hp = (HEADER *) buf;
1101 const HEADER *hp2 = (HEADER *) buf2;
1102 struct timespec now, timeout, finish;
1103 struct pollfd pfd[1];
1104 int ptimeout;
1105 struct sockaddr_in6 from;
1106 int resplen = 0;
1107 int n;
1108
1109 /*
1110 * Compute time for the total operation.
1111 */
1112 int seconds = (statp->retrans << ns);
1113 if (ns > 0)
1114 seconds /= statp->nscount;
1115 if (seconds <= 0)
1116 seconds = 1;
1117 bool single_request_reopen = (statp->options & RES_SNGLKUPREOP) != 0;
1118 bool single_request = (((statp->options & RES_SNGLKUP) != 0)
1119 | single_request_reopen);
1120 int save_gotsomewhere = *gotsomewhere;
1121
1122 int retval;
1123 retry_reopen:
1124 retval = reopen (statp, terrno, ns);
1125 if (retval <= 0)
1126 {
1127 if (resplen2 != NULL)
1128 *resplen2 = 0;
1129 return retval;
1130 }
1131 retry:
1132 evNowTime(&now);
1133 evConsTime(&timeout, seconds, 0);
1134 evAddTime(&finish, &now, &timeout);
1135 int need_recompute = 0;
1136 int nwritten = 0;
1137 int recvresp1 = 0;
1138 /* Skip the second response if there is no second query.
1139 To do that we mark the second response as received. */
1140 int recvresp2 = buf2 == NULL;
1141 pfd[0].fd = EXT(statp).nssocks[ns];
1142 pfd[0].events = POLLOUT;
1143 wait:
1144 if (need_recompute) {
1145 recompute_resend:
1146 evNowTime(&now);
1147 if (evCmpTime(finish, now) <= 0) {
1148 poll_err_out:
1149 Perror(statp, stderr, "poll", errno);
1150 return close_and_return_error (statp, resplen2);
1151 }
1152 evSubTime(&timeout, &finish, &now);
1153 need_recompute = 0;
1154 }
1155 /* Convert struct timespec in milliseconds. */
1156 ptimeout = timeout.tv_sec * 1000 + timeout.tv_nsec / 1000000;
1157
1158 n = 0;
1159 if (nwritten == 0)
1160 n = __poll (pfd, 1, 0);
1161 if (__glibc_unlikely (n == 0)) {
1162 n = __poll (pfd, 1, ptimeout);
1163 need_recompute = 1;
1164 }
1165 if (n == 0) {
1166 Dprint(statp->options & RES_DEBUG, (stdout, ";; timeout\n"));
1167 if (resplen > 1 && (recvresp1 || (buf2 != NULL && recvresp2)))
1168 {
1169 /* There are quite a few broken name servers out
1170 there which don't handle two outstanding
1171 requests from the same source. There are also
1172 broken firewall settings. If we time out after
1173 having received one answer switch to the mode
1174 where we send the second request only once we
1175 have received the first answer. */
1176 if (!single_request)
1177 {
1178 statp->options |= RES_SNGLKUP;
1179 single_request = true;
1180 *gotsomewhere = save_gotsomewhere;
1181 goto retry;
1182 }
1183 else if (!single_request_reopen)
1184 {
1185 statp->options |= RES_SNGLKUPREOP;
1186 single_request_reopen = true;
1187 *gotsomewhere = save_gotsomewhere;
1188 __res_iclose (statp, false);
1189 goto retry_reopen;
1190 }
1191
1192 *resplen2 = 1;
1193 return resplen;
1194 }
1195
1196 *gotsomewhere = 1;
1197 if (resplen2 != NULL)
1198 *resplen2 = 0;
1199 return 0;
1200 }
1201 if (n < 0) {
1202 if (errno == EINTR)
1203 goto recompute_resend;
1204
1205 goto poll_err_out;
1206 }
1207 __set_errno (0);
1208 if (pfd[0].revents & POLLOUT) {
1209#ifndef __ASSUME_SENDMMSG
1210 static int have_sendmmsg;
1211#else
1212# define have_sendmmsg 1
1213#endif
1214 if (have_sendmmsg >= 0 && nwritten == 0 && buf2 != NULL
1215 && !single_request)
1216 {
1217 struct iovec iov[2];
1218 struct mmsghdr reqs[2];
1219 reqs[0].msg_hdr.msg_name = NULL;
1220 reqs[0].msg_hdr.msg_namelen = 0;
1221 reqs[0].msg_hdr.msg_iov = &iov[0];
1222 reqs[0].msg_hdr.msg_iovlen = 1;
1223 iov[0].iov_base = (void *) buf;
1224 iov[0].iov_len = buflen;
1225 reqs[0].msg_hdr.msg_control = NULL;
1226 reqs[0].msg_hdr.msg_controllen = 0;
1227
1228 reqs[1].msg_hdr.msg_name = NULL;
1229 reqs[1].msg_hdr.msg_namelen = 0;
1230 reqs[1].msg_hdr.msg_iov = &iov[1];
1231 reqs[1].msg_hdr.msg_iovlen = 1;
1232 iov[1].iov_base = (void *) buf2;
1233 iov[1].iov_len = buflen2;
1234 reqs[1].msg_hdr.msg_control = NULL;
1235 reqs[1].msg_hdr.msg_controllen = 0;
1236
1237 int ndg = __sendmmsg (pfd[0].fd, reqs, 2, MSG_NOSIGNAL);
1238 if (__glibc_likely (ndg == 2))
1239 {
1240 if (reqs[0].msg_len != buflen
1241 || reqs[1].msg_len != buflen2)
1242 goto fail_sendmmsg;
1243
1244 pfd[0].events = POLLIN;
1245 nwritten += 2;
1246 }
1247 else if (ndg == 1 && reqs[0].msg_len == buflen)
1248 goto just_one;
1249 else if (ndg < 0 && (errno == EINTR || errno == EAGAIN))
1250 goto recompute_resend;
1251 else
1252 {
1253#ifndef __ASSUME_SENDMMSG
1254 if (__glibc_unlikely (have_sendmmsg == 0))
1255 {
1256 if (ndg < 0 && errno == ENOSYS)
1257 {
1258 have_sendmmsg = -1;
1259 goto try_send;
1260 }
1261 have_sendmmsg = 1;
1262 }
1263#endif
1264
1265 fail_sendmmsg:
1266 Perror(statp, stderr, "sendmmsg", errno);
1267 return close_and_return_error (statp, resplen2);
1268 }
1269 }
1270 else
1271 {
1272 ssize_t sr;
1273#ifndef __ASSUME_SENDMMSG
1274 try_send:
1275#endif
1276 if (nwritten != 0)
1277 sr = send (pfd[0].fd, buf2, buflen2, MSG_NOSIGNAL);
1278 else
1279 sr = send (pfd[0].fd, buf, buflen, MSG_NOSIGNAL);
1280
1281 if (sr != (nwritten != 0 ? buflen2 : buflen)) {
1282 if (errno == EINTR || errno == EAGAIN)
1283 goto recompute_resend;
1284 Perror(statp, stderr, "send", errno);
1285 return close_and_return_error (statp, resplen2);
1286 }
1287 just_one:
1288 if (nwritten != 0 || buf2 == NULL || single_request)
1289 pfd[0].events = POLLIN;
1290 else
1291 pfd[0].events = POLLIN | POLLOUT;
1292 ++nwritten;
1293 }
1294 goto wait;
1295 } else if (pfd[0].revents & POLLIN) {
1296 int *thisanssizp;
1297 u_char **thisansp;
1298 int *thisresplenp;
1299
1300 if ((recvresp1 | recvresp2) == 0 || buf2 == NULL) {
1301 /* We have not received any responses
1302 yet or we only have one response to
1303 receive. */
1304 thisanssizp = anssizp;
1305 thisansp = anscp ?: ansp;
1306 assert (anscp != NULL || ansp2 == NULL);
1307 thisresplenp = &resplen;
1308 } else {
1309 thisanssizp = anssizp2;
1310 thisansp = ansp2;
1311 thisresplenp = resplen2;
1312 }
1313
1314 if (*thisanssizp < MAXPACKET
1315 /* If the current buffer is not the the static
1316 user-supplied buffer then we can reallocate
1317 it. */
1318 && (thisansp != NULL && thisansp != ansp)
1319#ifdef FIONREAD
1320 /* Is the size too small? */
1321 && (ioctl (pfd[0].fd, FIONREAD, thisresplenp) < 0
1322 || *thisanssizp < *thisresplenp)
1323#endif
1324 ) {
1325 /* Always allocate MAXPACKET, callers expect
1326 this specific size. */
1327 u_char *newp = malloc (MAXPACKET);
1328 if (newp != NULL) {
1329 *thisanssizp = MAXPACKET;
1330 *thisansp = newp;
1331 if (thisansp == ansp2)
1332 *ansp2_malloced = 1;
1333 }
1334 }
1335 /* We could end up with truncation if anscp was NULL
1336 (not allowed to change caller's buffer) and the
1337 response buffer size is too small. This isn't a
1338 reliable way to detect truncation because the ioctl
1339 may be an inaccurate report of the UDP message size.
1340 Therefore we use this only to issue debug output.
1341 To do truncation accurately with UDP we need
1342 MSG_TRUNC which is only available on Linux. We
1343 can abstract out the Linux-specific feature in the
1344 future to detect truncation. */
1345 if (__glibc_unlikely (*thisanssizp < *thisresplenp)) {
1346 Dprint(statp->options & RES_DEBUG,
1347 (stdout, ";; response may be truncated (UDP)\n")
1348 );
1349 }
1350
1351 HEADER *anhp = (HEADER *) *thisansp;
1352 socklen_t fromlen = sizeof(struct sockaddr_in6);
1353 assert (sizeof(from) <= fromlen);
1354 *thisresplenp = recvfrom(pfd[0].fd, (char*)*thisansp,
1355 *thisanssizp, 0,
1356 (struct sockaddr *)&from, &fromlen);
1357 if (__glibc_unlikely (*thisresplenp <= 0)) {
1358 if (errno == EINTR || errno == EAGAIN) {
1359 need_recompute = 1;
1360 goto wait;
1361 }
1362 Perror(statp, stderr, "recvfrom", errno);
1363 return close_and_return_error (statp, resplen2);
1364 }
1365 *gotsomewhere = 1;
1366 if (__glibc_unlikely (*thisresplenp < HFIXEDSZ)) {
1367 /*
1368 * Undersized message.
1369 */
1370 Dprint(statp->options & RES_DEBUG,
1371 (stdout, ";; undersized: %d\n",
1372 *thisresplenp));
1373 *terrno = EMSGSIZE;
1374 return close_and_return_error (statp, resplen2);
1375 }
1376 if ((recvresp1 || hp->id != anhp->id)
1377 && (recvresp2 || hp2->id != anhp->id)) {
1378 /*
1379 * response from old query, ignore it.
1380 * XXX - potential security hazard could
1381 * be detected here.
1382 */
1383 DprintQ((statp->options & RES_DEBUG) ||
1384 (statp->pfcode & RES_PRF_REPLY),
1385 (stdout, ";; old answer:\n"),
1386 *thisansp,
1387 (*thisresplenp > *thisanssizp)
1388 ? *thisanssizp : *thisresplenp);
1389 goto wait;
1390 }
1391 if (!(statp->options & RES_INSECURE1) &&
1392 !res_ourserver_p(statp, &from)) {
1393 /*
1394 * response from wrong server? ignore it.
1395 * XXX - potential security hazard could
1396 * be detected here.
1397 */
1398 DprintQ((statp->options & RES_DEBUG) ||
1399 (statp->pfcode & RES_PRF_REPLY),
1400 (stdout, ";; not our server:\n"),
1401 *thisansp,
1402 (*thisresplenp > *thisanssizp)
1403 ? *thisanssizp : *thisresplenp);
1404 goto wait;
1405 }
1406#ifdef RES_USE_EDNS0
1407 if (anhp->rcode == FORMERR
1408 && (statp->options & RES_USE_EDNS0) != 0U) {
1409 /*
1410 * Do not retry if the server does not understand
1411 * EDNS0. The case has to be captured here, as
1412 * FORMERR packet do not carry query section, hence
1413 * res_queriesmatch() returns 0.
1414 */
1415 DprintQ(statp->options & RES_DEBUG,
1416 (stdout,
1417 "server rejected query with EDNS0:\n"),
1418 *thisansp,
1419 (*thisresplenp > *thisanssizp)
1420 ? *thisanssizp : *thisresplenp);
1421 /* record the error */
1422 statp->_flags |= RES_F_EDNS0ERR;
1423 return close_and_return_error (statp, resplen2);
1424 }
1425#endif
1426 if (!(statp->options & RES_INSECURE2)
1427 && (recvresp1 || !res_queriesmatch(buf, buf + buflen,
1428 *thisansp,
1429 *thisansp
1430 + *thisanssizp))
1431 && (recvresp2 || !res_queriesmatch(buf2, buf2 + buflen2,
1432 *thisansp,
1433 *thisansp
1434 + *thisanssizp))) {
1435 /*
1436 * response contains wrong query? ignore it.
1437 * XXX - potential security hazard could
1438 * be detected here.
1439 */
1440 DprintQ((statp->options & RES_DEBUG) ||
1441 (statp->pfcode & RES_PRF_REPLY),
1442 (stdout, ";; wrong query name:\n"),
1443 *thisansp,
1444 (*thisresplenp > *thisanssizp)
1445 ? *thisanssizp : *thisresplenp);
1446 goto wait;
1447 }
1448 if (anhp->rcode == SERVFAIL ||
1449 anhp->rcode == NOTIMP ||
1450 anhp->rcode == REFUSED) {
1451 DprintQ(statp->options & RES_DEBUG,
1452 (stdout, "server rejected query:\n"),
1453 *thisansp,
1454 (*thisresplenp > *thisanssizp)
1455 ? *thisanssizp : *thisresplenp);
1456
1457 next_ns:
1458 if (recvresp1 || (buf2 != NULL && recvresp2)) {
1459 *resplen2 = 0;
1460 return resplen;
1461 }
1462 if (buf2 != NULL)
1463 {
1464 /* No data from the first reply. */
1465 resplen = 0;
1466 /* We are waiting for a possible second reply. */
1467 if (hp->id == anhp->id)
1468 recvresp1 = 1;
1469 else
1470 recvresp2 = 1;
1471
1472 goto wait;
1473 }
1474
1475 /* don't retry if called from dig */
1476 if (!statp->pfcode)
1477 return close_and_return_error (statp, resplen2);
1478 __res_iclose(statp, false);
1479 }
1480 if (anhp->rcode == NOERROR && anhp->ancount == 0
1481 && anhp->aa == 0 && anhp->ra == 0 && anhp->arcount == 0) {
1482 DprintQ(statp->options & RES_DEBUG,
1483 (stdout, "referred query:\n"),
1484 *thisansp,
1485 (*thisresplenp > *thisanssizp)
1486 ? *thisanssizp : *thisresplenp);
1487 goto next_ns;
1488 }
1489 if (!(statp->options & RES_IGNTC) && anhp->tc) {
1490 /*
1491 * To get the rest of answer,
1492 * use TCP with same server.
1493 */
1494 Dprint(statp->options & RES_DEBUG,
1495 (stdout, ";; truncated answer\n"));
1496 *v_circuit = 1;
1497 __res_iclose(statp, false);
1498 // XXX if we have received one reply we could
1499 // XXX use it and not repeat it over TCP...
1500 if (resplen2 != NULL)
1501 *resplen2 = 0;
1502 return (1);
1503 }
1504 /* Mark which reply we received. */
1505 if (recvresp1 == 0 && hp->id == anhp->id)
1506 recvresp1 = 1;
1507 else
1508 recvresp2 = 1;
1509 /* Repeat waiting if we have a second answer to arrive. */
1510 if ((recvresp1 & recvresp2) == 0) {
1511 if (single_request) {
1512 pfd[0].events = POLLOUT;
1513 if (single_request_reopen) {
1514 __res_iclose (statp, false);
1515 retval = reopen (statp, terrno, ns);
1516 if (retval <= 0)
1517 {
1518 if (resplen2 != NULL)
1519 *resplen2 = 0;
1520 return retval;
1521 }
1522 pfd[0].fd = EXT(statp).nssocks[ns];
1523 }
1524 }
1525 goto wait;
1526 }
1527 /* All is well. We have received both responses (if
1528 two responses were requested). */
1529 return (resplen);
1530 } else if (pfd[0].revents & (POLLERR | POLLHUP | POLLNVAL))
1531 /* Something went wrong. We can stop trying. */
1532 return close_and_return_error (statp, resplen2);
1533 else {
1534 /* poll should not have returned > 0 in this case. */
1535 abort ();
1536 }
1537}
1538
1539#ifdef DEBUG
1540static void
1541Aerror(const res_state statp, FILE *file, const char *string, int error,
1542 const struct sockaddr *address)
1543{
1544 int save = errno;
1545
1546 if ((statp->options & RES_DEBUG) != 0) {
1547 char tmp[sizeof "xxxx.xxxx.xxxx.255.255.255.255"];
1548
1549 fprintf(file, "res_send: %s ([%s].%u): %s\n",
1550 string,
1551 (address->sa_family == AF_INET
1552 ? inet_ntop(address->sa_family,
1553 &((const struct sockaddr_in *) address)->sin_addr,
1554 tmp, sizeof tmp)
1555 : inet_ntop(address->sa_family,
1556 &((const struct sockaddr_in6 *) address)->sin6_addr,
1557 tmp, sizeof tmp)),
1558 (address->sa_family == AF_INET
1559 ? ntohs(((struct sockaddr_in *) address)->sin_port)
1560 : address->sa_family == AF_INET6
1561 ? ntohs(((struct sockaddr_in6 *) address)->sin6_port)
1562 : 0),
1563 strerror(error));
1564 }
1565 __set_errno (save);
1566}
1567
1568static void
1569Perror(const res_state statp, FILE *file, const char *string, int error) {
1570 int save = errno;
1571
1572 if ((statp->options & RES_DEBUG) != 0)
1573 fprintf(file, "res_send: %s: %s\n",
1574 string, strerror(error));
1575 __set_errno (save);
1576}
1577#endif
1578
1579static int
1580sock_eq(struct sockaddr_in6 *a1, struct sockaddr_in6 *a2) {
1581 if (a1->sin6_family == a2->sin6_family) {
1582 if (a1->sin6_family == AF_INET)
1583 return ((((struct sockaddr_in *)a1)->sin_port ==
1584 ((struct sockaddr_in *)a2)->sin_port) &&
1585 (((struct sockaddr_in *)a1)->sin_addr.s_addr ==
1586 ((struct sockaddr_in *)a2)->sin_addr.s_addr));
1587 else
1588 return ((a1->sin6_port == a2->sin6_port) &&
1589 !memcmp(&a1->sin6_addr, &a2->sin6_addr,
1590 sizeof (struct in6_addr)));
1591 }
1592 if (a1->sin6_family == AF_INET) {
1593 struct sockaddr_in6 *sap = a1;
1594 a1 = a2;
1595 a2 = sap;
1596 } /* assumes that AF_INET and AF_INET6 are the only possibilities */
1597 return ((a1->sin6_port == ((struct sockaddr_in *)a2)->sin_port) &&
1598 IN6_IS_ADDR_V4MAPPED(&a1->sin6_addr) &&
1599 (a1->sin6_addr.s6_addr32[3] ==
1600 ((struct sockaddr_in *)a2)->sin_addr.s_addr));
1601}
1602