PageRenderTime 55ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

lib/libc/resolv/res_send.c

http://www.minix3.org/
C | 1145 lines | 801 code | 82 blank | 262 comment | 189 complexity | 3cba7ee5ca0288fb4bfb897cb4f60a1d MD5 | raw file
Possible License(s): MIT, WTFPL, AGPL-1.0, BSD-3-Clause, GPL-3.0, LGPL-2.0, JSON, 0BSD
  1. /* $NetBSD: res_send.c,v 1.20 2009/10/24 17:24:01 christos Exp $ */
  2. /*
  3. * Portions Copyright (C) 2004-2009 Internet Systems Consortium, Inc. ("ISC")
  4. * Portions Copyright (C) 1996-2003 Internet Software Consortium.
  5. *
  6. * Permission to use, copy, modify, and/or distribute this software for any
  7. * purpose with or without fee is hereby granted, provided that the above
  8. * copyright notice and this permission notice appear in all copies.
  9. *
  10. * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  11. * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  12. * AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  13. * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  14. * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  15. * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  16. * PERFORMANCE OF THIS SOFTWARE.
  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. * 3. All advertising materials mentioning features or use of this software
  31. * must display the following acknowledgement:
  32. * This product includes software developed by the University of
  33. * California, Berkeley and its contributors.
  34. * 4. Neither the name of the University nor the names of its contributors
  35. * may be used to endorse or promote products derived from this software
  36. * without specific prior written permission.
  37. *
  38. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  39. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  40. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  41. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  42. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  43. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  44. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  45. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  46. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  47. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  48. * SUCH DAMAGE.
  49. */
  50. /*
  51. * Portions Copyright (c) 1993 by Digital Equipment Corporation.
  52. *
  53. * Permission to use, copy, modify, and distribute this software for any
  54. * purpose with or without fee is hereby granted, provided that the above
  55. * copyright notice and this permission notice appear in all copies, and that
  56. * the name of Digital Equipment Corporation not be used in advertising or
  57. * publicity pertaining to distribution of the document or software without
  58. * specific, written prior permission.
  59. *
  60. * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
  61. * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
  62. * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
  63. * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  64. * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  65. * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
  66. * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
  67. * SOFTWARE.
  68. */
  69. /*
  70. * Copyright (c) 2005 by Internet Systems Consortium, Inc. ("ISC")
  71. * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
  72. *
  73. * Permission to use, copy, modify, and distribute this software for any
  74. * purpose with or without fee is hereby granted, provided that the above
  75. * copyright notice and this permission notice appear in all copies.
  76. *
  77. * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
  78. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  79. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR
  80. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  81. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  82. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  83. * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  84. */
  85. #include <sys/cdefs.h>
  86. #if defined(LIBC_SCCS) && !defined(lint)
  87. #ifdef notdef
  88. static const char sccsid[] = "@(#)res_send.c 8.1 (Berkeley) 6/4/93";
  89. static const char rcsid[] = "Id: res_send.c,v 1.22 2009/01/22 23:49:23 tbox Exp";
  90. #else
  91. __RCSID("$NetBSD: res_send.c,v 1.20 2009/10/24 17:24:01 christos Exp $");
  92. #endif
  93. #endif /* LIBC_SCCS and not lint */
  94. /*! \file
  95. * \brief
  96. * Send query to name server and wait for reply.
  97. */
  98. #include "namespace.h"
  99. #include "port_before.h"
  100. #include "fd_setsize.h"
  101. #include <sys/types.h>
  102. #include <sys/param.h>
  103. #include <sys/time.h>
  104. #include <sys/socket.h>
  105. #include <sys/uio.h>
  106. #include <netinet/in.h>
  107. #include <arpa/nameser.h>
  108. #include <arpa/inet.h>
  109. #include <errno.h>
  110. #include <netdb.h>
  111. #include <resolv.h>
  112. #include <signal.h>
  113. #include <stdio.h>
  114. #include <stdlib.h>
  115. #include <string.h>
  116. #include <unistd.h>
  117. #include <isc/eventlib.h>
  118. #include "port_after.h"
  119. #if 0
  120. #ifdef __weak_alias
  121. __weak_alias(res_ourserver_p,__res_ourserver_p)
  122. __weak_alias(res_nameinquery,__res_nameinquery)
  123. __weak_alias(res_queriesmatch,__res_queriesmatch)
  124. __weak_alias(res_nsend,__res_nsend)
  125. #endif
  126. #endif
  127. #ifdef USE_POLL
  128. #ifdef HAVE_STROPTS_H
  129. #include <stropts.h>
  130. #endif
  131. #include <poll.h>
  132. #endif /* USE_POLL */
  133. /* Options. Leave them on. */
  134. #ifndef DEBUG
  135. #define DEBUG
  136. #endif
  137. #include "res_debug.h"
  138. #include "res_private.h"
  139. #define EXT(res) ((res)->_u._ext)
  140. #ifndef USE_POLL
  141. static const int highestFD = FD_SETSIZE - 1;
  142. #else
  143. static int highestFD = 0;
  144. #endif
  145. /* Forward. */
  146. static int get_salen __P((const struct sockaddr *));
  147. static struct sockaddr * get_nsaddr __P((res_state, size_t));
  148. static int send_vc(res_state, const u_char *, int,
  149. u_char *, int, int *, int);
  150. static int send_dg(res_state, const u_char *, int,
  151. u_char *, int, int *, int, int,
  152. int *, int *);
  153. static void Aerror(const res_state, FILE *, const char *, int,
  154. const struct sockaddr *, int);
  155. static void Perror(const res_state, FILE *, const char *, int);
  156. static int sock_eq(struct sockaddr *, struct sockaddr *);
  157. #if defined(NEED_PSELECT) && !defined(USE_POLL)
  158. static int pselect(int, void *, void *, void *,
  159. struct timespec *,
  160. const sigset_t *);
  161. #endif
  162. void res_pquery(const res_state, const u_char *, int, FILE *);
  163. static const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
  164. /* Public. */
  165. /*%
  166. * looks up "ina" in _res.ns_addr_list[]
  167. *
  168. * returns:
  169. *\li 0 : not found
  170. *\li >0 : found
  171. *
  172. * author:
  173. *\li paul vixie, 29may94
  174. */
  175. int
  176. res_ourserver_p(const res_state statp, const struct sockaddr *sa) {
  177. const struct sockaddr_in *inp, *srv;
  178. const struct sockaddr_in6 *in6p, *srv6;
  179. int ns;
  180. switch (sa->sa_family) {
  181. case AF_INET:
  182. inp = (const struct sockaddr_in *)(const void *)sa;
  183. for (ns = 0; ns < statp->nscount; ns++) {
  184. srv = (struct sockaddr_in *)(void *)get_nsaddr(statp, (size_t)ns);
  185. if (srv->sin_family == inp->sin_family &&
  186. srv->sin_port == inp->sin_port &&
  187. (srv->sin_addr.s_addr == INADDR_ANY ||
  188. srv->sin_addr.s_addr == inp->sin_addr.s_addr))
  189. return (1);
  190. }
  191. break;
  192. case AF_INET6:
  193. if (EXT(statp).ext == NULL)
  194. break;
  195. in6p = (const struct sockaddr_in6 *)(const void *)sa;
  196. for (ns = 0; ns < statp->nscount; ns++) {
  197. srv6 = (struct sockaddr_in6 *)(void *)get_nsaddr(statp, (size_t)ns);
  198. if (srv6->sin6_family == in6p->sin6_family &&
  199. srv6->sin6_port == in6p->sin6_port &&
  200. #ifdef HAVE_SIN6_SCOPE_ID
  201. (srv6->sin6_scope_id == 0 ||
  202. srv6->sin6_scope_id == in6p->sin6_scope_id) &&
  203. #endif
  204. (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
  205. IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
  206. return (1);
  207. }
  208. break;
  209. default:
  210. break;
  211. }
  212. return (0);
  213. }
  214. /*%
  215. * look for (name,type,class) in the query section of packet (buf,eom)
  216. *
  217. * requires:
  218. *\li buf + HFIXEDSZ <= eom
  219. *
  220. * returns:
  221. *\li -1 : format error
  222. *\li 0 : not found
  223. *\li >0 : found
  224. *
  225. * author:
  226. *\li paul vixie, 29may94
  227. */
  228. int
  229. res_nameinquery(const char *name, int type, int class,
  230. const u_char *buf, const u_char *eom)
  231. {
  232. const u_char *cp = buf + HFIXEDSZ;
  233. int qdcount = ntohs(((const HEADER*)(const void *)buf)->qdcount);
  234. while (qdcount-- > 0) {
  235. char tname[MAXDNAME+1];
  236. int n, ttype, tclass;
  237. n = dn_expand(buf, eom, cp, tname, sizeof tname);
  238. if (n < 0)
  239. return (-1);
  240. cp += n;
  241. if (cp + 2 * INT16SZ > eom)
  242. return (-1);
  243. ttype = ns_get16(cp); cp += INT16SZ;
  244. tclass = ns_get16(cp); cp += INT16SZ;
  245. if (ttype == type && tclass == class &&
  246. ns_samename(tname, name) == 1)
  247. return (1);
  248. }
  249. return (0);
  250. }
  251. /*%
  252. * is there a 1:1 mapping of (name,type,class)
  253. * in (buf1,eom1) and (buf2,eom2)?
  254. *
  255. * returns:
  256. *\li -1 : format error
  257. *\li 0 : not a 1:1 mapping
  258. *\li >0 : is a 1:1 mapping
  259. *
  260. * author:
  261. *\li paul vixie, 29may94
  262. */
  263. int
  264. res_queriesmatch(const u_char *buf1, const u_char *eom1,
  265. const u_char *buf2, const u_char *eom2)
  266. {
  267. const u_char *cp = buf1 + HFIXEDSZ;
  268. int qdcount = ntohs(((const HEADER*)(const void *)buf1)->qdcount);
  269. if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2)
  270. return (-1);
  271. /*
  272. * Only header section present in replies to
  273. * dynamic update packets.
  274. */
  275. if ((((const HEADER *)(const void *)buf1)->opcode == ns_o_update) &&
  276. (((const HEADER *)(const void *)buf2)->opcode == ns_o_update))
  277. return (1);
  278. if (qdcount != ntohs(((const HEADER*)(const void *)buf2)->qdcount))
  279. return (0);
  280. while (qdcount-- > 0) {
  281. char tname[MAXDNAME+1];
  282. int n, ttype, tclass;
  283. n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
  284. if (n < 0)
  285. return (-1);
  286. cp += n;
  287. if (cp + 2 * INT16SZ > eom1)
  288. return (-1);
  289. ttype = ns_get16(cp); cp += INT16SZ;
  290. tclass = ns_get16(cp); cp += INT16SZ;
  291. if (!res_nameinquery(tname, ttype, tclass, buf2, eom2))
  292. return (0);
  293. }
  294. return (1);
  295. }
  296. int
  297. res_nsend(res_state statp,
  298. const u_char *buf, int buflen, u_char *ans, int anssiz)
  299. {
  300. int gotsomewhere, terrno, tries, v_circuit, resplen, ns, n;
  301. char abuf[NI_MAXHOST];
  302. #ifdef USE_POLL
  303. highestFD = sysconf(_SC_OPEN_MAX) - 1;
  304. #endif
  305. (void)res_check(statp, NULL);
  306. /* No name servers or res_init() failure */
  307. if (statp->nscount == 0 || EXT(statp).ext == NULL) {
  308. errno = ESRCH;
  309. return (-1);
  310. }
  311. if (anssiz < HFIXEDSZ) {
  312. errno = EINVAL;
  313. return (-1);
  314. }
  315. DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_QUERY),
  316. (stdout, ";; res_send()\n"), buf, buflen);
  317. v_circuit = (statp->options & RES_USEVC) || buflen > PACKETSZ;
  318. gotsomewhere = 0;
  319. terrno = ETIMEDOUT;
  320. /*
  321. * If the ns_addr_list in the resolver context has changed, then
  322. * invalidate our cached copy and the associated timing data.
  323. */
  324. if (EXT(statp).nscount != 0) {
  325. int needclose = 0;
  326. struct sockaddr_storage peer;
  327. ISC_SOCKLEN_T peerlen;
  328. if (EXT(statp).nscount != statp->nscount)
  329. needclose++;
  330. else
  331. for (ns = 0; ns < statp->nscount; ns++) {
  332. if (statp->nsaddr_list[ns].sin_family &&
  333. !sock_eq((struct sockaddr *)(void *)&statp->nsaddr_list[ns],
  334. (struct sockaddr *)(void *)&EXT(statp).ext->nsaddrs[ns])) {
  335. needclose++;
  336. break;
  337. }
  338. if (EXT(statp).nssocks[ns] == -1)
  339. continue;
  340. peerlen = sizeof(peer);
  341. if (getpeername(EXT(statp).nssocks[ns],
  342. (struct sockaddr *)(void *)&peer, &peerlen) < 0) {
  343. needclose++;
  344. break;
  345. }
  346. if (!sock_eq((struct sockaddr *)(void *)&peer,
  347. get_nsaddr(statp, (size_t)ns))) {
  348. needclose++;
  349. break;
  350. }
  351. }
  352. if (needclose) {
  353. res_nclose(statp);
  354. EXT(statp).nscount = 0;
  355. }
  356. }
  357. /*
  358. * Maybe initialize our private copy of the ns_addr_list.
  359. */
  360. if (EXT(statp).nscount == 0) {
  361. for (ns = 0; ns < statp->nscount; ns++) {
  362. EXT(statp).nstimes[ns] = RES_MAXTIME;
  363. EXT(statp).nssocks[ns] = -1;
  364. if (!statp->nsaddr_list[ns].sin_family)
  365. continue;
  366. EXT(statp).ext->nsaddrs[ns].sin =
  367. statp->nsaddr_list[ns];
  368. }
  369. EXT(statp).nscount = statp->nscount;
  370. }
  371. /*
  372. * Some resolvers want to even out the load on their nameservers.
  373. * Note that RES_BLAST overrides RES_ROTATE.
  374. */
  375. if ((statp->options & RES_ROTATE) != 0U &&
  376. (statp->options & RES_BLAST) == 0U) {
  377. union res_sockaddr_union inu;
  378. struct sockaddr_in ina;
  379. int lastns = statp->nscount - 1;
  380. int fd;
  381. u_int16_t nstime;
  382. if (EXT(statp).ext != NULL)
  383. inu = EXT(statp).ext->nsaddrs[0];
  384. ina = statp->nsaddr_list[0];
  385. fd = EXT(statp).nssocks[0];
  386. nstime = EXT(statp).nstimes[0];
  387. for (ns = 0; ns < lastns; ns++) {
  388. if (EXT(statp).ext != NULL)
  389. EXT(statp).ext->nsaddrs[ns] =
  390. EXT(statp).ext->nsaddrs[ns + 1];
  391. statp->nsaddr_list[ns] = statp->nsaddr_list[ns + 1];
  392. EXT(statp).nssocks[ns] = EXT(statp).nssocks[ns + 1];
  393. EXT(statp).nstimes[ns] = EXT(statp).nstimes[ns + 1];
  394. }
  395. if (EXT(statp).ext != NULL)
  396. EXT(statp).ext->nsaddrs[lastns] = inu;
  397. statp->nsaddr_list[lastns] = ina;
  398. EXT(statp).nssocks[lastns] = fd;
  399. EXT(statp).nstimes[lastns] = nstime;
  400. }
  401. /*
  402. * Send request, RETRY times, or until successful.
  403. */
  404. for (tries = 0; tries < statp->retry; tries++) {
  405. for (ns = 0; ns < statp->nscount; ns++) {
  406. struct sockaddr *nsap;
  407. int nsaplen;
  408. nsap = get_nsaddr(statp, (size_t)ns);
  409. nsaplen = get_salen(nsap);
  410. statp->_flags &= ~RES_F_LASTMASK;
  411. statp->_flags |= (ns << RES_F_LASTSHIFT);
  412. same_ns:
  413. if (statp->qhook) {
  414. int done = 0, loops = 0;
  415. do {
  416. res_sendhookact act;
  417. act = (*statp->qhook)(&nsap, &buf, &buflen,
  418. ans, anssiz, &resplen);
  419. switch (act) {
  420. case res_goahead:
  421. done = 1;
  422. break;
  423. case res_nextns:
  424. res_nclose(statp);
  425. goto next_ns;
  426. case res_done:
  427. return (resplen);
  428. case res_modified:
  429. /* give the hook another try */
  430. if (++loops < 42) /*doug adams*/
  431. break;
  432. /*FALLTHROUGH*/
  433. case res_error:
  434. /*FALLTHROUGH*/
  435. default:
  436. goto fail;
  437. }
  438. } while (!done);
  439. }
  440. Dprint(((statp->options & RES_DEBUG) &&
  441. getnameinfo(nsap, (socklen_t)nsaplen, abuf, sizeof(abuf),
  442. NULL, 0, niflags) == 0),
  443. (stdout, ";; Querying server (# %d) address = %s\n",
  444. ns + 1, abuf));
  445. if (v_circuit) {
  446. /* Use VC; at most one attempt per server. */
  447. tries = statp->retry;
  448. n = send_vc(statp, buf, buflen, ans, anssiz, &terrno,
  449. ns);
  450. if (n < 0)
  451. goto fail;
  452. if (n == 0)
  453. goto next_ns;
  454. resplen = n;
  455. } else {
  456. /* Use datagrams. */
  457. n = send_dg(statp, buf, buflen, ans, anssiz, &terrno,
  458. ns, tries, &v_circuit, &gotsomewhere);
  459. if (n < 0)
  460. goto fail;
  461. if (n == 0)
  462. goto next_ns;
  463. if (v_circuit)
  464. goto same_ns;
  465. resplen = n;
  466. }
  467. Dprint((statp->options & RES_DEBUG) ||
  468. ((statp->pfcode & RES_PRF_REPLY) &&
  469. (statp->pfcode & RES_PRF_HEAD1)),
  470. (stdout, ";; got answer:\n"));
  471. DprintQ((statp->options & RES_DEBUG) ||
  472. (statp->pfcode & RES_PRF_REPLY),
  473. (stdout, "%s", ""),
  474. ans, (resplen > anssiz) ? anssiz : resplen);
  475. /*
  476. * If we have temporarily opened a virtual circuit,
  477. * or if we haven't been asked to keep a socket open,
  478. * close the socket.
  479. */
  480. if ((v_circuit && (statp->options & RES_USEVC) == 0U) ||
  481. (statp->options & RES_STAYOPEN) == 0U) {
  482. res_nclose(statp);
  483. }
  484. if (statp->rhook) {
  485. int done = 0, loops = 0;
  486. do {
  487. res_sendhookact act;
  488. act = (*statp->rhook)(nsap, buf, buflen,
  489. ans, anssiz, &resplen);
  490. switch (act) {
  491. case res_goahead:
  492. case res_done:
  493. done = 1;
  494. break;
  495. case res_nextns:
  496. res_nclose(statp);
  497. goto next_ns;
  498. case res_modified:
  499. /* give the hook another try */
  500. if (++loops < 42) /*doug adams*/
  501. break;
  502. /*FALLTHROUGH*/
  503. case res_error:
  504. /*FALLTHROUGH*/
  505. default:
  506. goto fail;
  507. }
  508. } while (!done);
  509. }
  510. return (resplen);
  511. next_ns: ;
  512. } /*foreach ns*/
  513. } /*foreach retry*/
  514. res_nclose(statp);
  515. if (!v_circuit) {
  516. if (!gotsomewhere)
  517. errno = ECONNREFUSED; /*%< no nameservers found */
  518. else
  519. errno = ETIMEDOUT; /*%< no answer obtained */
  520. } else
  521. errno = terrno;
  522. return (-1);
  523. fail:
  524. res_nclose(statp);
  525. return (-1);
  526. }
  527. /* Private */
  528. static int
  529. get_salen(sa)
  530. const struct sockaddr *sa;
  531. {
  532. #ifdef HAVE_SA_LEN
  533. /* There are people do not set sa_len. Be forgiving to them. */
  534. if (sa->sa_len)
  535. return (sa->sa_len);
  536. #endif
  537. if (sa->sa_family == AF_INET)
  538. return (sizeof(struct sockaddr_in));
  539. else if (sa->sa_family == AF_INET6)
  540. return (sizeof(struct sockaddr_in6));
  541. else
  542. return (0); /*%< unknown, die on connect */
  543. }
  544. /*%
  545. * pick appropriate nsaddr_list for use. see res_init() for initialization.
  546. */
  547. static struct sockaddr *
  548. get_nsaddr(statp, n)
  549. res_state statp;
  550. size_t n;
  551. {
  552. if (!statp->nsaddr_list[n].sin_family && EXT(statp).ext) {
  553. /*
  554. * - EXT(statp).ext->nsaddrs[n] holds an address that is larger
  555. * than struct sockaddr, and
  556. * - user code did not update statp->nsaddr_list[n].
  557. */
  558. return (struct sockaddr *)(void *)&EXT(statp).ext->nsaddrs[n];
  559. } else {
  560. /*
  561. * - user code updated statp->nsaddr_list[n], or
  562. * - statp->nsaddr_list[n] has the same content as
  563. * EXT(statp).ext->nsaddrs[n].
  564. */
  565. return (struct sockaddr *)(void *)&statp->nsaddr_list[n];
  566. }
  567. }
  568. static int
  569. send_vc(res_state statp,
  570. const u_char *buf, int buflen, u_char *ans, int anssiz,
  571. int *terrno, int ns)
  572. {
  573. const HEADER *hp = (const HEADER *)(const void *)buf;
  574. HEADER *anhp = (HEADER *)(void *)ans;
  575. struct sockaddr *nsap;
  576. int nsaplen;
  577. int truncating, connreset, resplen, n;
  578. struct iovec iov[2];
  579. u_short len;
  580. u_char *cp;
  581. void *tmp;
  582. #ifdef SO_NOSIGPIPE
  583. int on = 1;
  584. #endif
  585. nsap = get_nsaddr(statp, (size_t)ns);
  586. nsaplen = get_salen(nsap);
  587. connreset = 0;
  588. same_ns:
  589. truncating = 0;
  590. /* Are we still talking to whom we want to talk to? */
  591. if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
  592. struct sockaddr_storage peer;
  593. ISC_SOCKLEN_T size = sizeof peer;
  594. if (getpeername(statp->_vcsock,
  595. (struct sockaddr *)(void *)&peer, &size) < 0 ||
  596. !sock_eq((struct sockaddr *)(void *)&peer, nsap)) {
  597. res_nclose(statp);
  598. statp->_flags &= ~RES_F_VC;
  599. }
  600. }
  601. if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
  602. if (statp->_vcsock >= 0)
  603. res_nclose(statp);
  604. statp->_vcsock = socket(nsap->sa_family, SOCK_STREAM, 0);
  605. if (statp->_vcsock > highestFD) {
  606. res_nclose(statp);
  607. errno = ENOTSOCK;
  608. }
  609. if (statp->_vcsock < 0) {
  610. switch (errno) {
  611. case EPROTONOSUPPORT:
  612. #ifdef EPFNOSUPPORT
  613. case EPFNOSUPPORT:
  614. #endif
  615. case EAFNOSUPPORT:
  616. Perror(statp, stderr, "socket(vc)", errno);
  617. return (0);
  618. default:
  619. *terrno = errno;
  620. Perror(statp, stderr, "socket(vc)", errno);
  621. return (-1);
  622. }
  623. }
  624. #ifdef SO_NOSIGPIPE
  625. /*
  626. * Disable generation of SIGPIPE when writing to a closed
  627. * socket. Write should return -1 and set errno to EPIPE
  628. * instead.
  629. *
  630. * Push on even if setsockopt(SO_NOSIGPIPE) fails.
  631. */
  632. (void)setsockopt(statp->_vcsock, SOL_SOCKET, SO_NOSIGPIPE, &on,
  633. sizeof(on));
  634. #endif
  635. errno = 0;
  636. if (connect(statp->_vcsock, nsap, (socklen_t)nsaplen) < 0) {
  637. *terrno = errno;
  638. Aerror(statp, stderr, "connect/vc", errno, nsap,
  639. nsaplen);
  640. res_nclose(statp);
  641. return (0);
  642. }
  643. statp->_flags |= RES_F_VC;
  644. }
  645. /*
  646. * Send length & message
  647. */
  648. ns_put16((u_short)buflen, (u_char*)(void *)&len);
  649. iov[0] = evConsIovec(&len, INT16SZ);
  650. DE_CONST(buf, tmp);
  651. iov[1] = evConsIovec(tmp, (size_t)buflen);
  652. if (writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
  653. *terrno = errno;
  654. Perror(statp, stderr, "write failed", errno);
  655. res_nclose(statp);
  656. return (0);
  657. }
  658. /*
  659. * Receive length & response
  660. */
  661. read_len:
  662. cp = ans;
  663. len = INT16SZ;
  664. while ((n = read(statp->_vcsock, (char *)cp, (size_t)len)) > 0) {
  665. cp += n;
  666. if ((len -= n) == 0)
  667. break;
  668. }
  669. if (n <= 0) {
  670. *terrno = errno;
  671. Perror(statp, stderr, "read failed", errno);
  672. res_nclose(statp);
  673. /*
  674. * A long running process might get its TCP
  675. * connection reset if the remote server was
  676. * restarted. Requery the server instead of
  677. * trying a new one. When there is only one
  678. * server, this means that a query might work
  679. * instead of failing. We only allow one reset
  680. * per query to prevent looping.
  681. */
  682. if (*terrno == ECONNRESET && !connreset) {
  683. connreset = 1;
  684. res_nclose(statp);
  685. goto same_ns;
  686. }
  687. res_nclose(statp);
  688. return (0);
  689. }
  690. resplen = ns_get16(ans);
  691. if (resplen > anssiz) {
  692. Dprint(statp->options & RES_DEBUG,
  693. (stdout, ";; response truncated\n")
  694. );
  695. truncating = 1;
  696. len = anssiz;
  697. } else
  698. len = resplen;
  699. if (len < HFIXEDSZ) {
  700. /*
  701. * Undersized message.
  702. */
  703. Dprint(statp->options & RES_DEBUG,
  704. (stdout, ";; undersized: %d\n", len));
  705. *terrno = EMSGSIZE;
  706. res_nclose(statp);
  707. return (0);
  708. }
  709. cp = ans;
  710. while (len != 0 && (n = read(statp->_vcsock, (char *)cp, (size_t)len)) > 0){
  711. cp += n;
  712. len -= n;
  713. }
  714. if (n <= 0) {
  715. *terrno = errno;
  716. Perror(statp, stderr, "read(vc)", errno);
  717. res_nclose(statp);
  718. return (0);
  719. }
  720. if (truncating) {
  721. /*
  722. * Flush rest of answer so connection stays in synch.
  723. */
  724. anhp->tc = 1;
  725. len = resplen - anssiz;
  726. while (len != 0) {
  727. char junk[PACKETSZ];
  728. n = read(statp->_vcsock, junk,
  729. (len > sizeof junk) ? sizeof junk : len);
  730. if (n > 0)
  731. len -= n;
  732. else
  733. break;
  734. }
  735. }
  736. /*
  737. * If the calling applicating has bailed out of
  738. * a previous call and failed to arrange to have
  739. * the circuit closed or the server has got
  740. * itself confused, then drop the packet and
  741. * wait for the correct one.
  742. */
  743. if (hp->id != anhp->id) {
  744. DprintQ((statp->options & RES_DEBUG) ||
  745. (statp->pfcode & RES_PRF_REPLY),
  746. (stdout, ";; old answer (unexpected):\n"),
  747. ans, (resplen > anssiz) ? anssiz: resplen);
  748. goto read_len;
  749. }
  750. /*
  751. * All is well, or the error is fatal. Signal that the
  752. * next nameserver ought not be tried.
  753. */
  754. return (resplen);
  755. }
  756. static int
  757. send_dg(res_state statp, const u_char *buf, int buflen, u_char *ans,
  758. int anssiz, int *terrno, int ns, int tries, int *v_circuit,
  759. int *gotsomewhere)
  760. {
  761. const HEADER *hp = (const HEADER *)(const void *)buf;
  762. HEADER *anhp = (HEADER *)(void *)ans;
  763. const struct sockaddr *nsap;
  764. int nsaplen;
  765. struct timespec now, timeout, finish;
  766. struct sockaddr_storage from;
  767. ISC_SOCKLEN_T fromlen;
  768. int resplen, seconds, n, s;
  769. #ifdef USE_POLL
  770. int polltimeout;
  771. struct pollfd pollfd;
  772. #else
  773. fd_set dsmask;
  774. #endif
  775. nsap = get_nsaddr(statp, (size_t)ns);
  776. nsaplen = get_salen(nsap);
  777. if (EXT(statp).nssocks[ns] == -1) {
  778. EXT(statp).nssocks[ns] = socket(nsap->sa_family, SOCK_DGRAM, 0);
  779. if (EXT(statp).nssocks[ns] > highestFD) {
  780. res_nclose(statp);
  781. errno = ENOTSOCK;
  782. }
  783. if (EXT(statp).nssocks[ns] < 0) {
  784. switch (errno) {
  785. case EPROTONOSUPPORT:
  786. #ifdef EPFNOSUPPORT
  787. case EPFNOSUPPORT:
  788. #endif
  789. case EAFNOSUPPORT:
  790. Perror(statp, stderr, "socket(dg)", errno);
  791. return (0);
  792. default:
  793. *terrno = errno;
  794. Perror(statp, stderr, "socket(dg)", errno);
  795. return (-1);
  796. }
  797. }
  798. #ifndef CANNOT_CONNECT_DGRAM
  799. /*
  800. * On a 4.3BSD+ machine (client and server,
  801. * actually), sending to a nameserver datagram
  802. * port with no nameserver will cause an
  803. * ICMP port unreachable message to be returned.
  804. * If our datagram socket is "connected" to the
  805. * server, we get an ECONNREFUSED error on the next
  806. * socket operation, and select returns if the
  807. * error message is received. We can thus detect
  808. * the absence of a nameserver without timing out.
  809. */
  810. if (connect(EXT(statp).nssocks[ns], nsap, (socklen_t)nsaplen) < 0) {
  811. Aerror(statp, stderr, "connect(dg)", errno, nsap,
  812. nsaplen);
  813. res_nclose(statp);
  814. return (0);
  815. }
  816. #endif /* !CANNOT_CONNECT_DGRAM */
  817. Dprint(statp->options & RES_DEBUG,
  818. (stdout, ";; new DG socket\n"))
  819. }
  820. s = EXT(statp).nssocks[ns];
  821. #ifndef CANNOT_CONNECT_DGRAM
  822. if (send(s, (const char*)buf, (size_t)buflen, 0) != buflen) {
  823. Perror(statp, stderr, "send", errno);
  824. res_nclose(statp);
  825. return (0);
  826. }
  827. #else /* !CANNOT_CONNECT_DGRAM */
  828. if (sendto(s, (const char*)buf, buflen, 0, nsap, nsaplen) != buflen)
  829. {
  830. Aerror(statp, stderr, "sendto", errno, nsap, nsaplen);
  831. res_nclose(statp);
  832. return (0);
  833. }
  834. #endif /* !CANNOT_CONNECT_DGRAM */
  835. /*
  836. * Wait for reply.
  837. */
  838. seconds = (statp->retrans << tries);
  839. if (ns > 0)
  840. seconds /= statp->nscount;
  841. if (seconds <= 0)
  842. seconds = 1;
  843. now = evNowTime();
  844. timeout = evConsTime((long)seconds, 0L);
  845. finish = evAddTime(now, timeout);
  846. goto nonow;
  847. wait:
  848. now = evNowTime();
  849. nonow:
  850. #ifndef USE_POLL
  851. FD_ZERO(&dsmask);
  852. FD_SET(s, &dsmask);
  853. if (evCmpTime(finish, now) > 0)
  854. timeout = evSubTime(finish, now);
  855. else
  856. timeout = evConsTime(0L, 0L);
  857. n = pselect(s + 1, &dsmask, NULL, NULL, &timeout, NULL);
  858. #else
  859. timeout = evSubTime(finish, now);
  860. if (timeout.tv_sec < 0)
  861. timeout = evConsTime(0L, 0L);
  862. polltimeout = 1000*(int)timeout.tv_sec +
  863. (int)timeout.tv_nsec/1000000;
  864. pollfd.fd = s;
  865. pollfd.events = POLLRDNORM;
  866. n = poll(&pollfd, 1, polltimeout);
  867. #endif /* USE_POLL */
  868. if (n == 0) {
  869. Dprint(statp->options & RES_DEBUG, (stdout, ";; timeout\n"));
  870. *gotsomewhere = 1;
  871. return (0);
  872. }
  873. if (n < 0) {
  874. if (errno == EINTR)
  875. goto wait;
  876. #ifndef USE_POLL
  877. Perror(statp, stderr, "select", errno);
  878. #else
  879. Perror(statp, stderr, "poll", errno);
  880. #endif /* USE_POLL */
  881. res_nclose(statp);
  882. return (0);
  883. }
  884. errno = 0;
  885. fromlen = sizeof(from);
  886. resplen = recvfrom(s, (char*)ans, (size_t)anssiz,0,
  887. (struct sockaddr *)(void *)&from, &fromlen);
  888. if (resplen <= 0) {
  889. Perror(statp, stderr, "recvfrom", errno);
  890. res_nclose(statp);
  891. return (0);
  892. }
  893. *gotsomewhere = 1;
  894. if (resplen < HFIXEDSZ) {
  895. /*
  896. * Undersized message.
  897. */
  898. Dprint(statp->options & RES_DEBUG,
  899. (stdout, ";; undersized: %d\n",
  900. resplen));
  901. *terrno = EMSGSIZE;
  902. res_nclose(statp);
  903. return (0);
  904. }
  905. if (hp->id != anhp->id) {
  906. /*
  907. * response from old query, ignore it.
  908. * XXX - potential security hazard could
  909. * be detected here.
  910. */
  911. DprintQ((statp->options & RES_DEBUG) ||
  912. (statp->pfcode & RES_PRF_REPLY),
  913. (stdout, ";; old answer:\n"),
  914. ans, (resplen > anssiz) ? anssiz : resplen);
  915. goto wait;
  916. }
  917. if (!(statp->options & RES_INSECURE1) &&
  918. !res_ourserver_p(statp, (struct sockaddr *)(void *)&from)) {
  919. /*
  920. * response from wrong server? ignore it.
  921. * XXX - potential security hazard could
  922. * be detected here.
  923. */
  924. DprintQ((statp->options & RES_DEBUG) ||
  925. (statp->pfcode & RES_PRF_REPLY),
  926. (stdout, ";; not our server:\n"),
  927. ans, (resplen > anssiz) ? anssiz : resplen);
  928. goto wait;
  929. }
  930. #ifdef RES_USE_EDNS0
  931. if (anhp->rcode == FORMERR && (statp->options & RES_USE_EDNS0) != 0U) {
  932. /*
  933. * Do not retry if the server do not understand EDNS0.
  934. * The case has to be captured here, as FORMERR packet do not
  935. * carry query section, hence res_queriesmatch() returns 0.
  936. */
  937. DprintQ(statp->options & RES_DEBUG,
  938. (stdout, "server rejected query with EDNS0:\n"),
  939. ans, (resplen > anssiz) ? anssiz : resplen);
  940. /* record the error */
  941. statp->_flags |= RES_F_EDNS0ERR;
  942. res_nclose(statp);
  943. return (0);
  944. }
  945. #endif
  946. if (!(statp->options & RES_INSECURE2) &&
  947. !res_queriesmatch(buf, buf + buflen,
  948. ans, ans + anssiz)) {
  949. /*
  950. * response contains wrong query? ignore it.
  951. * XXX - potential security hazard could
  952. * be detected here.
  953. */
  954. DprintQ((statp->options & RES_DEBUG) ||
  955. (statp->pfcode & RES_PRF_REPLY),
  956. (stdout, ";; wrong query name:\n"),
  957. ans, (resplen > anssiz) ? anssiz : resplen);
  958. goto wait;
  959. }
  960. if (anhp->rcode == SERVFAIL ||
  961. anhp->rcode == NOTIMP ||
  962. anhp->rcode == REFUSED) {
  963. DprintQ(statp->options & RES_DEBUG,
  964. (stdout, "server rejected query:\n"),
  965. ans, (resplen > anssiz) ? anssiz : resplen);
  966. res_nclose(statp);
  967. /* don't retry if called from dig */
  968. if (!statp->pfcode)
  969. return (0);
  970. }
  971. if (!(statp->options & RES_IGNTC) && anhp->tc) {
  972. /*
  973. * To get the rest of answer,
  974. * use TCP with same server.
  975. */
  976. Dprint(statp->options & RES_DEBUG,
  977. (stdout, ";; truncated answer\n"));
  978. *v_circuit = 1;
  979. res_nclose(statp);
  980. return (1);
  981. }
  982. /*
  983. * All is well, or the error is fatal. Signal that the
  984. * next nameserver ought not be tried.
  985. */
  986. return (resplen);
  987. }
  988. static void
  989. Aerror(const res_state statp, FILE *file, const char *string, int error,
  990. const struct sockaddr *address, int alen)
  991. {
  992. int save = errno;
  993. char hbuf[NI_MAXHOST];
  994. char sbuf[NI_MAXSERV];
  995. if ((statp->options & RES_DEBUG) != 0U) {
  996. if (getnameinfo(address, (socklen_t)alen, hbuf, sizeof(hbuf),
  997. sbuf, sizeof(sbuf), niflags)) {
  998. strncpy(hbuf, "?", sizeof(hbuf) - 1);
  999. hbuf[sizeof(hbuf) - 1] = '\0';
  1000. strncpy(sbuf, "?", sizeof(sbuf) - 1);
  1001. sbuf[sizeof(sbuf) - 1] = '\0';
  1002. }
  1003. fprintf(file, "res_send: %s ([%s].%s): %s\n",
  1004. string, hbuf, sbuf, strerror(error));
  1005. }
  1006. errno = save;
  1007. }
  1008. static void
  1009. Perror(const res_state statp, FILE *file, const char *string, int error) {
  1010. int save = errno;
  1011. if ((statp->options & RES_DEBUG) != 0U)
  1012. fprintf(file, "res_send: %s: %s\n",
  1013. string, strerror(error));
  1014. errno = save;
  1015. }
  1016. static int
  1017. sock_eq(struct sockaddr *a, struct sockaddr *b) {
  1018. struct sockaddr_in *a4, *b4;
  1019. struct sockaddr_in6 *a6, *b6;
  1020. if (a->sa_family != b->sa_family)
  1021. return 0;
  1022. switch (a->sa_family) {
  1023. case AF_INET:
  1024. a4 = (struct sockaddr_in *)(void *)a;
  1025. b4 = (struct sockaddr_in *)(void *)b;
  1026. return a4->sin_port == b4->sin_port &&
  1027. a4->sin_addr.s_addr == b4->sin_addr.s_addr;
  1028. case AF_INET6:
  1029. a6 = (struct sockaddr_in6 *)(void *)a;
  1030. b6 = (struct sockaddr_in6 *)(void *)b;
  1031. return a6->sin6_port == b6->sin6_port &&
  1032. #ifdef HAVE_SIN6_SCOPE_ID
  1033. a6->sin6_scope_id == b6->sin6_scope_id &&
  1034. #endif
  1035. IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
  1036. default:
  1037. return 0;
  1038. }
  1039. }
  1040. #if defined(NEED_PSELECT) && !defined(USE_POLL)
  1041. /* XXX needs to move to the porting library. */
  1042. static int
  1043. pselect(int nfds, void *rfds, void *wfds, void *efds,
  1044. struct timespec *tsp, const sigset_t *sigmask)
  1045. {
  1046. struct timeval tv, *tvp;
  1047. sigset_t sigs;
  1048. int n;
  1049. if (tsp) {
  1050. tvp = &tv;
  1051. tv = evTimeVal(*tsp);
  1052. } else
  1053. tvp = NULL;
  1054. if (sigmask)
  1055. sigprocmask(SIG_SETMASK, sigmask, &sigs);
  1056. n = select(nfds, rfds, wfds, efds, tvp);
  1057. if (sigmask)
  1058. sigprocmask(SIG_SETMASK, &sigs, NULL);
  1059. if (tsp)
  1060. *tsp = evTimeSpec(tv);
  1061. return (n);
  1062. }
  1063. #endif