res_send.c 43 KB

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