resolv.c 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116
  1. /* resolv.c: DNS Resolver
  2. *
  3. * Copyright (C) 1998 Kenneth Albanowski <kjahds@kjahds.com>,
  4. * The Silver Hammer Group, Ltd.
  5. *
  6. * This library is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Library General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2 of the License, or (at your option) any later version.
  10. */
  11. /*
  12. * Portions Copyright (c) 1985, 1993
  13. * The Regents of the University of California. All rights reserved.
  14. *
  15. * Redistribution and use in source and binary forms, with or without
  16. * modification, are permitted provided that the following conditions
  17. * are met:
  18. * 1. Redistributions of source code must retain the above copyright
  19. * notice, this list of conditions and the following disclaimer.
  20. * 2. Redistributions in binary form must reproduce the above copyright
  21. * notice, this list of conditions and the following disclaimer in the
  22. * documentation and/or other materials provided with the distribution.
  23. * 4. Neither the name of the University nor the names of its contributors
  24. * may be used to endorse or promote products derived from this software
  25. * without specific prior written permission.
  26. *
  27. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  28. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  29. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  30. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  31. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  32. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  33. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  34. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  35. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  36. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  37. * SUCH DAMAGE.
  38. */
  39. /*
  40. * Portions Copyright (c) 1993 by Digital Equipment Corporation.
  41. *
  42. * Permission to use, copy, modify, and distribute this software for any
  43. * purpose with or without fee is hereby granted, provided that the above
  44. * copyright notice and this permission notice appear in all copies, and that
  45. * the name of Digital Equipment Corporation not be used in advertising or
  46. * publicity pertaining to distribution of the document or software without
  47. * specific, written prior permission.
  48. *
  49. * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
  50. * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
  51. * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
  52. * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  53. * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  54. * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
  55. * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
  56. * SOFTWARE.
  57. */
  58. /*
  59. * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
  60. *
  61. * Permission to use, copy, modify, and distribute this software for any
  62. * purpose with or without fee is hereby granted, provided that the above
  63. * copyright notice and this permission notice appear in all copies.
  64. *
  65. * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
  66. * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
  67. * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
  68. * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  69. * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  70. * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
  71. * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
  72. * SOFTWARE.
  73. */
  74. /*
  75. *
  76. * 5-Oct-2000 W. Greathouse wgreathouse@smva.com
  77. * Fix memory leak and memory corruption.
  78. * -- Every name resolution resulted in
  79. * a new parse of resolv.conf and new
  80. * copy of nameservers allocated by
  81. * strdup.
  82. * -- Every name resolution resulted in
  83. * a new read of resolv.conf without
  84. * resetting index from prior read...
  85. * resulting in exceeding array bounds.
  86. *
  87. * Limit nameservers read from resolv.conf
  88. *
  89. * Add "search" domains from resolv.conf
  90. *
  91. * Some systems will return a security
  92. * signature along with query answer for
  93. * dynamic DNS entries.
  94. * -- skip/ignore this answer
  95. *
  96. * Include arpa/nameser.h for defines.
  97. *
  98. * General cleanup
  99. *
  100. * 20-Jun-2001 Michal Moskal <malekith@pld.org.pl>
  101. * partial IPv6 support (i.e. gethostbyname2() and resolve_address2()
  102. * functions added), IPv6 nameservers are also supported.
  103. *
  104. * 6-Oct-2001 Jari Korva <jari.korva@iki.fi>
  105. * more IPv6 support (IPv6 support for gethostbyaddr();
  106. * address family parameter and improved IPv6 support for get_hosts_byname
  107. * and read_etc_hosts; getnameinfo() port from glibc; defined
  108. * defined ip6addr_any and in6addr_loopback)
  109. *
  110. * 2-Feb-2002 Erik Andersen <andersen@codepoet.org>
  111. * Added gethostent(), sethostent(), and endhostent()
  112. *
  113. * 17-Aug-2002 Manuel Novoa III <mjn3@codepoet.org>
  114. * Fixed __read_etc_hosts_r to return alias list, and modified buffer
  115. * allocation accordingly. See MAX_ALIASES and ALIAS_DIM below.
  116. * This fixes the segfault in the Python 2.2.1 socket test.
  117. *
  118. * 04-Jan-2003 Jay Kulpinski <jskulpin@berkshire.rr.com>
  119. * Fixed __decode_dotted to count the terminating null character
  120. * in a host name.
  121. *
  122. * 02-Oct-2003 Tony J. White <tjw@tjw.org>
  123. * Lifted dn_expand() and dependent ns_name_uncompress(), ns_name_unpack(),
  124. * and ns_name_ntop() from glibc 2.3.2 for compatibility with ipsec-tools
  125. * and openldap.
  126. *
  127. * 7-Sep-2004 Erik Andersen <andersen@codepoet.org>
  128. * Added gethostent_r()
  129. *
  130. */
  131. /* Nota bene:
  132. The whole resolver code has several (severe) problems:
  133. - it doesn't even build without IPv4, i.e. !UCLIBC_HAS_IPV4 but only IPv6
  134. - it is way too big
  135. Both points above are considered bugs, patches/reimplementations welcome.
  136. */
  137. #define __FORCE_GLIBC
  138. #include <features.h>
  139. #include <string.h>
  140. #include <stdio.h>
  141. #include <signal.h>
  142. #include <errno.h>
  143. #include <sys/poll.h>
  144. #include <sys/socket.h>
  145. #include <sys/types.h>
  146. #include <sys/time.h>
  147. #include <netinet/in.h>
  148. #include <arpa/inet.h>
  149. #include <stdlib.h>
  150. #include <unistd.h>
  151. #include <resolv.h>
  152. #include <netdb.h>
  153. #include <ctype.h>
  154. #include <stdbool.h>
  155. #include <time.h>
  156. #include <arpa/nameser.h>
  157. #include <sys/utsname.h>
  158. #include <sys/un.h>
  159. #include <bits/uClibc_mutex.h>
  160. /* poll() is not supported in kernel <= 2.0, therefore if __NR_poll is
  161. * not available, we assume an old Linux kernel is in use and we will
  162. * use select() instead. */
  163. #include <sys/syscall.h>
  164. #ifndef __NR_poll
  165. # define USE_SELECT
  166. #endif
  167. /* Experimentally off - libc_hidden_proto(memcpy) */
  168. /* Experimentally off - libc_hidden_proto(memset) */
  169. /* Experimentally off - libc_hidden_proto(memmove) */
  170. /* Experimentally off - libc_hidden_proto(strchr) */
  171. /* Experimentally off - libc_hidden_proto(strcmp) */
  172. /* Experimentally off - libc_hidden_proto(strcpy) */
  173. /* Experimentally off - libc_hidden_proto(strdup) */
  174. /* Experimentally off - libc_hidden_proto(strlen) */
  175. /* Experimentally off - libc_hidden_proto(strncat) */
  176. /* Experimentally off - libc_hidden_proto(strncpy) */
  177. /* libc_hidden_proto(strnlen) */
  178. /* Experimentally off - libc_hidden_proto(strstr) */
  179. /* Experimentally off - libc_hidden_proto(strcasecmp) */
  180. /* libc_hidden_proto(socket) */
  181. /* libc_hidden_proto(close) */
  182. /* libc_hidden_proto(fopen) */
  183. /* libc_hidden_proto(fclose) */
  184. /* libc_hidden_proto(random) */
  185. /* libc_hidden_proto(getservbyport) */
  186. /* libc_hidden_proto(gethostname) */
  187. /* libc_hidden_proto(uname) */
  188. /* libc_hidden_proto(inet_addr) */
  189. /* libc_hidden_proto(inet_aton) */
  190. /* libc_hidden_proto(inet_pton) */
  191. /* libc_hidden_proto(inet_ntop) */
  192. /* libc_hidden_proto(connect) */
  193. /* libc_hidden_proto(poll) */
  194. /* libc_hidden_proto(select) */
  195. /* libc_hidden_proto(recv) */
  196. /* libc_hidden_proto(send) */
  197. /* libc_hidden_proto(printf) */
  198. /* libc_hidden_proto(sprintf) */
  199. /* libc_hidden_proto(snprintf) */
  200. /* libc_hidden_proto(fgets) */
  201. /* libc_hidden_proto(getnameinfo) */
  202. /* libc_hidden_proto(gethostbyname) */
  203. /* libc_hidden_proto(gethostbyname_r) */
  204. /* libc_hidden_proto(gethostbyname2_r) */
  205. /* libc_hidden_proto(gethostbyaddr) */
  206. /* libc_hidden_proto(gethostbyaddr_r) */
  207. /* libc_hidden_proto(ns_name_uncompress) */
  208. /* libc_hidden_proto(ns_name_unpack) */
  209. /* libc_hidden_proto(ns_name_ntop) */
  210. /* libc_hidden_proto(res_init) */
  211. /* libc_hidden_proto(res_query) */
  212. /* libc_hidden_proto(res_querydomain) */
  213. /* libc_hidden_proto(gethostent_r) */
  214. /* libc_hidden_proto(fprintf) */
  215. /* libc_hidden_proto(__h_errno_location) */
  216. #ifdef __UCLIBC_HAS_XLOCALE__
  217. /* libc_hidden_proto(__ctype_b_loc) */
  218. #elif defined __UCLIBC_HAS_CTYPE_TABLES__
  219. /* libc_hidden_proto(__ctype_b) */
  220. #endif
  221. #if defined __UCLIBC_HAS_IPV4__ && defined __UCLIBC_HAS_IPV6__
  222. #define IF_HAS_BOTH(...) __VA_ARGS__
  223. #else
  224. #define IF_HAS_BOTH(...)
  225. #endif
  226. #define MAX_RECURSE 5
  227. #define MAX_ALIASES 5
  228. /* 1:ip + 1:full + MAX_ALIASES:aliases + 1:NULL */
  229. #define ALIAS_DIM (2 + MAX_ALIASES + 1)
  230. #undef DEBUG
  231. /* #define DEBUG */
  232. #ifdef DEBUG
  233. #define DPRINTF(X,args...) fprintf(stderr, X, ##args)
  234. #else
  235. #define DPRINTF(X,args...)
  236. #endif
  237. #undef ARRAY_SIZE
  238. #define ARRAY_SIZE(v) (sizeof(v) / sizeof((v)[0]))
  239. /* Make sure the incoming char * buffer is aligned enough to handle our random
  240. * structures. This define is the same as we use for malloc alignment (which
  241. * has same requirements). The offset is the number of bytes we need to adjust
  242. * in order to attain desired alignment.
  243. */
  244. #define ALIGN_ATTR __alignof__(double __attribute_aligned__ (sizeof(size_t)))
  245. #define ALIGN_BUFFER_OFFSET(buf) ((ALIGN_ATTR - ((size_t)buf % ALIGN_ATTR)) % ALIGN_ATTR)
  246. /* Structs */
  247. struct resolv_header {
  248. int id;
  249. int qr,opcode,aa,tc,rd,ra,rcode;
  250. int qdcount;
  251. int ancount;
  252. int nscount;
  253. int arcount;
  254. };
  255. struct resolv_question {
  256. char * dotted;
  257. int qtype;
  258. int qclass;
  259. };
  260. struct resolv_answer {
  261. char * dotted;
  262. int atype;
  263. int aclass;
  264. int ttl;
  265. int rdlength;
  266. const unsigned char * rdata;
  267. int rdoffset;
  268. char* buf;
  269. size_t buflen;
  270. size_t add_count;
  271. };
  272. enum etc_hosts_action {
  273. GET_HOSTS_BYNAME = 0,
  274. GETHOSTENT,
  275. GET_HOSTS_BYADDR,
  276. };
  277. typedef union sockaddr46_t {
  278. struct sockaddr sa;
  279. #ifdef __UCLIBC_HAS_IPV4__
  280. struct sockaddr_in sa4;
  281. #endif
  282. #ifdef __UCLIBC_HAS_IPV6__
  283. struct sockaddr_in6 sa6;
  284. #endif
  285. } sockaddr46_t;
  286. __UCLIBC_MUTEX_EXTERN(__resolv_lock);
  287. /* Protected by __resolv_lock */
  288. extern void (*__res_sync)(void) attribute_hidden;
  289. /*extern uint32_t __resolv_opts attribute_hidden; */
  290. extern unsigned __nameservers attribute_hidden;
  291. extern unsigned __searchdomains attribute_hidden;
  292. extern sockaddr46_t *__nameserver attribute_hidden;
  293. extern char **__searchdomain attribute_hidden;
  294. #ifdef __UCLIBC_HAS_IPV4__
  295. extern const struct sockaddr_in __local_nameserver attribute_hidden;
  296. #else
  297. extern const struct sockaddr_in6 __local_nameserver attribute_hidden;
  298. #endif
  299. /* Arbitrary */
  300. #define MAXLEN_searchdomain 128
  301. /* function prototypes */
  302. extern int __get_hosts_byname_r(const char * name, int type,
  303. struct hostent * result_buf,
  304. char * buf, size_t buflen,
  305. struct hostent ** result,
  306. int * h_errnop) attribute_hidden;
  307. extern int __get_hosts_byaddr_r(const char * addr, int len, int type,
  308. struct hostent * result_buf,
  309. char * buf, size_t buflen,
  310. struct hostent ** result,
  311. int * h_errnop) attribute_hidden;
  312. extern FILE * __open_etc_hosts(void) attribute_hidden;
  313. extern int __read_etc_hosts_r(FILE *fp, const char * name, int type,
  314. enum etc_hosts_action action,
  315. struct hostent * result_buf,
  316. char * buf, size_t buflen,
  317. struct hostent ** result,
  318. int * h_errnop) attribute_hidden;
  319. extern int __dns_lookup(const char * name, int type,
  320. unsigned char ** outpacket,
  321. struct resolv_answer * a) attribute_hidden;
  322. extern int __encode_dotted(const char * dotted, unsigned char * dest, int maxlen) attribute_hidden;
  323. extern int __decode_dotted(const unsigned char * const message, int offset,
  324. char * dest, int maxlen) attribute_hidden;
  325. extern int __length_dotted(const unsigned char * const message, int offset) attribute_hidden;
  326. extern int __encode_header(struct resolv_header * h, unsigned char * dest, int maxlen) attribute_hidden;
  327. extern void __decode_header(unsigned char * data, struct resolv_header * h) attribute_hidden;
  328. extern int __encode_question(const struct resolv_question * const q,
  329. unsigned char * dest, int maxlen) attribute_hidden;
  330. extern int __decode_question(const unsigned char * const message, int offset,
  331. struct resolv_question * q) attribute_hidden;
  332. extern int __encode_answer(struct resolv_answer * a,
  333. unsigned char * dest, int maxlen) attribute_hidden;
  334. extern int __decode_answer(const unsigned char * message, int offset,
  335. int len, struct resolv_answer * a) attribute_hidden;
  336. extern int __length_question(const unsigned char * const message, int offset) attribute_hidden;
  337. extern void __open_nameservers(void) attribute_hidden;
  338. extern void __close_nameservers(void) attribute_hidden;
  339. extern int __dn_expand(const u_char *, const u_char *, const u_char *,
  340. char *, int);
  341. /*
  342. * Theory of operation.
  343. *
  344. * gethostbyname, getaddrinfo and friends end up here, and they sometimes
  345. * need to talk to DNS servers. In order to do this, we need to read /etc/resolv.conf
  346. * and determine servers' addresses and the like. resolv.conf format:
  347. *
  348. * nameserver <IP[v6]>
  349. * Address of DNS server. Cumulative.
  350. * If not specified, assumed to be on localhost.
  351. * search <domain1>[ <domain2>]...
  352. * Append these domains to unqualified names.
  353. * See ndots:n option.
  354. * $LOCALDOMAIN (space-separated list) overrides this.
  355. * domain <domain>
  356. * Effectively same as "search" with one domain.
  357. * If no "domain" line is present, the domain is determined
  358. * from the local host name returned by gethostname();
  359. * the domain part is taken to be everything after the first dot.
  360. * If there are no dots, there will be no "domain".
  361. * The domain and search keywords are mutually exclusive.
  362. * If more than one instance of these keywords is present,
  363. * the last instance wins.
  364. * sortlist 130.155.160.0[/255.255.240.0] 130.155.0.0
  365. * Allows addresses returned by gethostbyname to be sorted.
  366. * Not supported.
  367. * options option[ option]...
  368. * (so far we support none)
  369. * $RES_OPTIONS (space-separated list) is to be added to "options"
  370. * debug sets RES_DEBUG in _res.options
  371. * ndots:n how many dots there should be so that name will be tried
  372. * first as an absolute name before any search list elements
  373. * are appended to it. Default 1
  374. * timeout:n how long to wait for response. Default 5
  375. * (sun seems to have retrans:n synonym)
  376. * attempts:n number of rounds to do before giving up and returning
  377. * an error. Default 2
  378. * (sun seems to have retry:n synonym)
  379. * rotate sets RES_ROTATE in _res.options, round robin
  380. * selection of nameservers. Otherwise try
  381. * the first listed server first every time
  382. * no-check-names
  383. * sets RES_NOCHECKNAME in _res.options, which disables
  384. * checking of incoming host names for invalid characters
  385. * such as underscore (_), non-ASCII, or control characters
  386. * inet6 sets RES_USE_INET6 in _res.options. Try a AAAA query
  387. * before an A query inside the gethostbyname(), and map
  388. * IPv4 responses in IPv6 "tunnelled form" if no AAAA records
  389. * are found but an A record set exists
  390. * no_tld_query (FreeBSDism?)
  391. * do not attempt to resolve names without dots
  392. *
  393. * We will read and analyze /etc/resolv.conf as needed before
  394. * we do a DNS request. This happens in __dns_lookup.
  395. * (TODO: also re-parse it after a timeout, to catch updates).
  396. *
  397. * BSD has res_init routine which is used to initialize resolver state
  398. * which is held in global structure _res.
  399. * Generally, programs call res_init, then fiddle with _res.XXX
  400. * (_res.options and _res.nscount, _res.nsaddr_list[N]
  401. * are popular targets of fiddling) and expect subsequent calls
  402. * to gethostbyname, getaddrinfo, etc to use modified information.
  403. *
  404. * However, historical _res structure is quite awkward.
  405. * Using it for storing /etc/resolv.conf info is not desirable,
  406. * and __dns_lookup does not use it.
  407. *
  408. * We would like to avoid using it unless absolutely necessary.
  409. * If user doesn't use res_init, we should arrange it so that
  410. * _res structure doesn't even *get linked in* into user's application
  411. * (imagine static uclibc build here).
  412. *
  413. * The solution is a __res_sync function pointer, which is normally NULL.
  414. * But if res_init is called, it gets set and any subsequent gethostbyname
  415. * et al "syncronizes" our internal structures with potentially
  416. * modified _res.XXX stuff by calling __res_sync.
  417. * The trick here is that if res_init is not used and not linked in,
  418. * gethostbyname itself won't reference _res and _res won't be linked in
  419. * either. Other possible methods like
  420. * if (__res_sync_just_an_int_flag)
  421. * __sync_me_with_res()
  422. * would pull in __sync_me_with_res, which pulls in _res. Bad.
  423. */
  424. #ifdef L_encodeh
  425. int attribute_hidden __encode_header(struct resolv_header *h, unsigned char *dest, int maxlen)
  426. {
  427. if (maxlen < HFIXEDSZ)
  428. return -1;
  429. dest[0] = (h->id & 0xff00) >> 8;
  430. dest[1] = (h->id & 0x00ff) >> 0;
  431. dest[2] = (h->qr ? 0x80 : 0) |
  432. ((h->opcode & 0x0f) << 3) |
  433. (h->aa ? 0x04 : 0) |
  434. (h->tc ? 0x02 : 0) |
  435. (h->rd ? 0x01 : 0);
  436. dest[3] = (h->ra ? 0x80 : 0) | (h->rcode & 0x0f);
  437. dest[4] = (h->qdcount & 0xff00) >> 8;
  438. dest[5] = (h->qdcount & 0x00ff) >> 0;
  439. dest[6] = (h->ancount & 0xff00) >> 8;
  440. dest[7] = (h->ancount & 0x00ff) >> 0;
  441. dest[8] = (h->nscount & 0xff00) >> 8;
  442. dest[9] = (h->nscount & 0x00ff) >> 0;
  443. dest[10] = (h->arcount & 0xff00) >> 8;
  444. dest[11] = (h->arcount & 0x00ff) >> 0;
  445. return HFIXEDSZ;
  446. }
  447. #endif
  448. #ifdef L_decodeh
  449. void attribute_hidden __decode_header(unsigned char *data, struct resolv_header *h)
  450. {
  451. h->id = (data[0] << 8) | data[1];
  452. h->qr = (data[2] & 0x80) ? 1 : 0;
  453. h->opcode = (data[2] >> 3) & 0x0f;
  454. h->aa = (data[2] & 0x04) ? 1 : 0;
  455. h->tc = (data[2] & 0x02) ? 1 : 0;
  456. h->rd = (data[2] & 0x01) ? 1 : 0;
  457. h->ra = (data[3] & 0x80) ? 1 : 0;
  458. h->rcode = data[3] & 0x0f;
  459. h->qdcount = (data[4] << 8) | data[5];
  460. h->ancount = (data[6] << 8) | data[7];
  461. h->nscount = (data[8] << 8) | data[9];
  462. h->arcount = (data[10] << 8) | data[11];
  463. }
  464. #endif
  465. #ifdef L_encoded
  466. /* Encode a dotted string into nameserver transport-level encoding.
  467. This routine is fairly dumb, and doesn't attempt to compress
  468. the data */
  469. int attribute_hidden __encode_dotted(const char *dotted, unsigned char *dest, int maxlen)
  470. {
  471. unsigned used = 0;
  472. while (dotted && *dotted) {
  473. char *c = strchr(dotted, '.');
  474. int l = c ? c - dotted : strlen(dotted);
  475. /* two consecutive dots are not valid */
  476. if (l == 0)
  477. return -1;
  478. if (l >= (maxlen - used - 1))
  479. return -1;
  480. dest[used++] = l;
  481. memcpy(dest + used, dotted, l);
  482. used += l;
  483. if (!c)
  484. break;
  485. dotted = c + 1;
  486. }
  487. if (maxlen < 1)
  488. return -1;
  489. dest[used++] = 0;
  490. return used;
  491. }
  492. #endif
  493. #ifdef L_decoded
  494. /* Decode a dotted string from nameserver transport-level encoding.
  495. This routine understands compressed data. */
  496. int attribute_hidden __decode_dotted(const unsigned char * const data, int offset,
  497. char *dest, int maxlen)
  498. {
  499. int l;
  500. bool measure = 1;
  501. unsigned total = 0;
  502. unsigned used = 0;
  503. if (!data)
  504. return -1;
  505. while ((l = data[offset++])) {
  506. if (measure)
  507. total++;
  508. if ((l & 0xc0) == (0xc0)) {
  509. if (measure)
  510. total++;
  511. /* compressed item, redirect */
  512. offset = ((l & 0x3f) << 8) | data[offset];
  513. measure = 0;
  514. continue;
  515. }
  516. if ((used + l + 1) >= maxlen)
  517. return -1;
  518. memcpy(dest + used, data + offset, l);
  519. offset += l;
  520. used += l;
  521. if (measure)
  522. total += l;
  523. if (data[offset] != 0)
  524. dest[used++] = '.';
  525. else
  526. dest[used++] = '\0';
  527. }
  528. /* The null byte must be counted too */
  529. if (measure)
  530. total++;
  531. DPRINTF("Total decode len = %d\n", total);
  532. return total;
  533. }
  534. #endif
  535. #ifdef L_lengthd
  536. /* Returns -1 only if data == NULL */
  537. int attribute_hidden __length_dotted(const unsigned char * const data, int offset)
  538. {
  539. int orig_offset = offset;
  540. int l;
  541. if (!data)
  542. return -1;
  543. while ((l = data[offset++])) {
  544. if ((l & 0xc0) == (0xc0)) {
  545. offset++;
  546. break;
  547. }
  548. offset += l;
  549. }
  550. return offset - orig_offset;
  551. }
  552. #endif
  553. #ifdef L_encodeq
  554. int attribute_hidden __encode_question(const struct resolv_question * const q,
  555. unsigned char *dest, int maxlen)
  556. {
  557. int i;
  558. i = __encode_dotted(q->dotted, dest, maxlen);
  559. if (i < 0)
  560. return i;
  561. dest += i;
  562. maxlen -= i;
  563. if (maxlen < 4)
  564. return -1;
  565. dest[0] = (q->qtype & 0xff00) >> 8;
  566. dest[1] = (q->qtype & 0x00ff) >> 0;
  567. dest[2] = (q->qclass & 0xff00) >> 8;
  568. dest[3] = (q->qclass & 0x00ff) >> 0;
  569. return i + 4;
  570. }
  571. #endif
  572. #ifdef L_decodeq
  573. int attribute_hidden __decode_question(const unsigned char * const message, int offset,
  574. struct resolv_question *q)
  575. {
  576. char temp[256];
  577. int i;
  578. i = __decode_dotted(message, offset, temp, sizeof(temp));
  579. if (i < 0)
  580. return i;
  581. offset += i;
  582. /*TODO: what if strdup fails? */
  583. q->dotted = strdup(temp);
  584. q->qtype = (message[offset + 0] << 8) | message[offset + 1];
  585. q->qclass = (message[offset + 2] << 8) | message[offset + 3];
  586. return i + 4;
  587. }
  588. #endif
  589. #ifdef L_lengthq
  590. /* Returns -1 only if message == NULL */
  591. int attribute_hidden __length_question(const unsigned char * const message, int offset)
  592. {
  593. int i;
  594. /* returns -1 only if message == NULL */
  595. i = __length_dotted(message, offset);
  596. if (i < 0)
  597. return i;
  598. return i + 4;
  599. }
  600. #endif
  601. #ifdef L_encodea
  602. int attribute_hidden __encode_answer(struct resolv_answer *a, unsigned char *dest, int maxlen)
  603. {
  604. int i;
  605. i = __encode_dotted(a->dotted, dest, maxlen);
  606. if (i < 0)
  607. return i;
  608. dest += i;
  609. maxlen -= i;
  610. if (maxlen < (RRFIXEDSZ + a->rdlength))
  611. return -1;
  612. *dest++ = (a->atype & 0xff00) >> 8;
  613. *dest++ = (a->atype & 0x00ff) >> 0;
  614. *dest++ = (a->aclass & 0xff00) >> 8;
  615. *dest++ = (a->aclass & 0x00ff) >> 0;
  616. *dest++ = (a->ttl & 0xff000000) >> 24;
  617. *dest++ = (a->ttl & 0x00ff0000) >> 16;
  618. *dest++ = (a->ttl & 0x0000ff00) >> 8;
  619. *dest++ = (a->ttl & 0x000000ff) >> 0;
  620. *dest++ = (a->rdlength & 0xff00) >> 8;
  621. *dest++ = (a->rdlength & 0x00ff) >> 0;
  622. memcpy(dest, a->rdata, a->rdlength);
  623. return i + RRFIXEDSZ + a->rdlength;
  624. }
  625. #endif
  626. #ifdef L_decodea
  627. int attribute_hidden __decode_answer(const unsigned char *message, int offset,
  628. int len, struct resolv_answer *a)
  629. {
  630. char temp[256];
  631. int i;
  632. DPRINTF("decode_answer(start): off %d, len %d\n", offset, len);
  633. i = __decode_dotted(message, offset, temp, sizeof(temp));
  634. if (i < 0)
  635. return i;
  636. message += offset + i;
  637. len -= i + RRFIXEDSZ + offset;
  638. if (len < 0) {
  639. DPRINTF("decode_answer: off %d, len %d, i %d\n", offset, len, i);
  640. return len;
  641. }
  642. /* TODO: what if strdup fails? */
  643. a->dotted = strdup(temp);
  644. a->atype = (message[0] << 8) | message[1];
  645. message += 2;
  646. a->aclass = (message[0] << 8) | message[1];
  647. message += 2;
  648. a->ttl = (message[0] << 24) |
  649. (message[1] << 16) | (message[2] << 8) | (message[3] << 0);
  650. message += 4;
  651. a->rdlength = (message[0] << 8) | message[1];
  652. message += 2;
  653. a->rdata = message;
  654. a->rdoffset = offset + i + RRFIXEDSZ;
  655. DPRINTF("i=%d,rdlength=%d\n", i, a->rdlength);
  656. if (len < a->rdlength)
  657. return -1;
  658. return i + RRFIXEDSZ + a->rdlength;
  659. }
  660. #endif
  661. #ifdef CURRENTLY_UNUSED
  662. #ifdef L_encodep
  663. int __encode_packet(struct resolv_header *h,
  664. struct resolv_question **q,
  665. struct resolv_answer **an,
  666. struct resolv_answer **ns,
  667. struct resolv_answer **ar,
  668. unsigned char *dest, int maxlen) attribute_hidden;
  669. int __encode_packet(struct resolv_header *h,
  670. struct resolv_question **q,
  671. struct resolv_answer **an,
  672. struct resolv_answer **ns,
  673. struct resolv_answer **ar,
  674. unsigned char *dest, int maxlen)
  675. {
  676. int i, total = 0;
  677. unsigned j;
  678. i = __encode_header(h, dest, maxlen);
  679. if (i < 0)
  680. return i;
  681. dest += i;
  682. maxlen -= i;
  683. total += i;
  684. for (j = 0; j < h->qdcount; j++) {
  685. i = __encode_question(q[j], dest, maxlen);
  686. if (i < 0)
  687. return i;
  688. dest += i;
  689. maxlen -= i;
  690. total += i;
  691. }
  692. for (j = 0; j < h->ancount; j++) {
  693. i = __encode_answer(an[j], dest, maxlen);
  694. if (i < 0)
  695. return i;
  696. dest += i;
  697. maxlen -= i;
  698. total += i;
  699. }
  700. for (j = 0; j < h->nscount; j++) {
  701. i = __encode_answer(ns[j], dest, maxlen);
  702. if (i < 0)
  703. return i;
  704. dest += i;
  705. maxlen -= i;
  706. total += i;
  707. }
  708. for (j = 0; j < h->arcount; j++) {
  709. i = __encode_answer(ar[j], dest, maxlen);
  710. if (i < 0)
  711. return i;
  712. dest += i;
  713. maxlen -= i;
  714. total += i;
  715. }
  716. return total;
  717. }
  718. #endif
  719. #ifdef L_decodep
  720. int __decode_packet(unsigned char *data, struct resolv_header *h) attribute_hidden;
  721. int __decode_packet(unsigned char *data, struct resolv_header *h)
  722. {
  723. __decode_header(data, h);
  724. return HFIXEDSZ;
  725. }
  726. #endif
  727. #ifdef L_formquery
  728. int __form_query(int id, const char *name, int type, unsigned char *packet, int maxlen);
  729. int __form_query(int id, const char *name, int type, unsigned char *packet,
  730. int maxlen)
  731. {
  732. struct resolv_header h;
  733. struct resolv_question q;
  734. int i, j;
  735. memset(&h, 0, sizeof(h));
  736. h.id = id;
  737. h.qdcount = 1;
  738. q.dotted = (char *) name;
  739. q.qtype = type;
  740. q.qclass = C_IN; /* CLASS_IN */
  741. i = __encode_header(&h, packet, maxlen);
  742. if (i < 0)
  743. return i;
  744. j = __encode_question(&q, packet + i, maxlen - i);
  745. if (j < 0)
  746. return j;
  747. return i + j;
  748. }
  749. #endif
  750. #endif /* CURRENTLY_UNUSED */
  751. #ifdef L_opennameservers
  752. # if __BYTE_ORDER == __LITTLE_ENDIAN
  753. #define NAMESERVER_PORT_N (__bswap_constant_16(NAMESERVER_PORT))
  754. #else
  755. #define NAMESERVER_PORT_N NAMESERVER_PORT
  756. #endif
  757. __UCLIBC_MUTEX_INIT(__resolv_lock, PTHREAD_MUTEX_INITIALIZER);
  758. /* Protected by __resolv_lock */
  759. void (*__res_sync)(void);
  760. /*uint32_t __resolv_opts; */
  761. unsigned __nameservers;
  762. unsigned __searchdomains;
  763. sockaddr46_t *__nameserver;
  764. char **__searchdomain;
  765. #ifdef __UCLIBC_HAS_IPV4__
  766. const struct sockaddr_in __local_nameserver = {
  767. .sin_family = AF_INET,
  768. .sin_port = NAMESERVER_PORT_N,
  769. };
  770. #else
  771. const struct sockaddr_in6 __local_nameserver = {
  772. .sin6_family = AF_INET6,
  773. .sin6_port = NAMESERVER_PORT_N,
  774. };
  775. #endif
  776. /* Helpers. Both stop on EOL, if it's '\n', it is converted to NUL first */
  777. static char *skip_nospace(char *p)
  778. {
  779. while (*p != '\0' && !isspace(*p)) {
  780. if (*p == '\n') {
  781. *p = '\0';
  782. break;
  783. }
  784. p++;
  785. }
  786. return p;
  787. }
  788. static char *skip_and_NUL_space(char *p)
  789. {
  790. /* NB: '\n' is not isspace! */
  791. while (1) {
  792. char c = *p;
  793. if (c == '\0' || !isspace(c))
  794. break;
  795. *p = '\0';
  796. if (c == '\n' || c == '#')
  797. break;
  798. p++;
  799. }
  800. return p;
  801. }
  802. /* Must be called under __resolv_lock. */
  803. void attribute_hidden __open_nameservers(void)
  804. {
  805. static uint8_t last_time;
  806. char szBuffer[MAXLEN_searchdomain];
  807. FILE *fp;
  808. int i;
  809. sockaddr46_t sa;
  810. if (!__res_sync) {
  811. /* Provide for periodic reread of /etc/resolv.conf */
  812. /* cur_time "ticks" every 256 seconds */
  813. uint8_t cur_time = ((unsigned)time(NULL)) >> 8;
  814. if (last_time != cur_time) {
  815. last_time = cur_time;
  816. __close_nameservers(); /* force config reread */
  817. }
  818. }
  819. if (__nameservers)
  820. goto sync;
  821. fp = fopen("/etc/resolv.conf", "r");
  822. if (!fp) {
  823. /* If we do not have a pre-populated /etc/resolv.conf then
  824. try to use the one from /etc/config which exists on numerous
  825. systems ranging from some uClinux to IRIX installations and
  826. may be the only /etc dir that was mounted rw. */
  827. fp = fopen("/etc/config/resolv.conf", "r");
  828. }
  829. if (fp) {
  830. while (fgets(szBuffer, sizeof(szBuffer), fp) != NULL) {
  831. void *ptr;
  832. char *keyword, *p;
  833. keyword = p = skip_and_NUL_space(szBuffer);
  834. /* skip keyword */
  835. p = skip_nospace(p);
  836. /* find next word */
  837. p = skip_and_NUL_space(p);
  838. if (strcmp(keyword, "nameserver") == 0) {
  839. /* terminate IP addr */
  840. *skip_nospace(p) = '\0';
  841. memset(&sa, 0, sizeof(sa));
  842. if (0) /* nothing */;
  843. #ifdef __UCLIBC_HAS_IPV6__
  844. else if (inet_pton(AF_INET6, p, &sa.sa6.sin6_addr) > 0) {
  845. sa.sa6.sin6_family = AF_INET6;
  846. sa.sa6.sin6_port = htons(NAMESERVER_PORT);
  847. }
  848. #endif
  849. #ifdef __UCLIBC_HAS_IPV4__
  850. else if (inet_pton(AF_INET, p, &sa.sa4.sin_addr) > 0) {
  851. sa.sa4.sin_family = AF_INET;
  852. sa.sa4.sin_port = htons(NAMESERVER_PORT);
  853. }
  854. #endif
  855. else
  856. continue; /* garbage on this line */
  857. ptr = realloc(__nameserver, (__nameservers + 1) * sizeof(__nameserver[0]));
  858. if (!ptr)
  859. continue;
  860. __nameserver = ptr;
  861. __nameserver[__nameservers++] = sa; /* struct copy */
  862. continue;
  863. }
  864. if (strcmp(keyword, "domain") == 0 || strcmp(keyword, "search") == 0) {
  865. char *p1;
  866. /* free old domains ("last 'domain' or 'search' wins" rule) */
  867. while (__searchdomains)
  868. free(__searchdomain[--__searchdomains]);
  869. /*free(__searchdomain);*/
  870. /*__searchdomain = NULL; - not necessary */
  871. next_word:
  872. /* terminate current word */
  873. p1 = skip_nospace(p);
  874. /* find next word (maybe) */
  875. p1 = skip_and_NUL_space(p1);
  876. /* add it */
  877. ptr = realloc(__searchdomain, (__searchdomains + 1) * sizeof(__searchdomain[0]));
  878. if (!ptr)
  879. continue;
  880. __searchdomain = ptr;
  881. /* NB: strlen(p) <= MAXLEN_searchdomain) because szBuffer[] is smaller */
  882. ptr = strdup(p);
  883. if (!ptr)
  884. continue;
  885. DPRINTF("adding search %s\n", (char*)ptr);
  886. __searchdomain[__searchdomains++] = (char*)ptr;
  887. p = p1;
  888. if (*p)
  889. goto next_word;
  890. continue;
  891. }
  892. /* if (strcmp(keyword, "sortlist") == 0)... */
  893. /* if (strcmp(keyword, "options") == 0)... */
  894. }
  895. fclose(fp);
  896. }
  897. if (__nameservers == 0) {
  898. /* Have to handle malloc failure! What a mess...
  899. * And it's not only here, we need to be careful
  900. * to never write into __nameserver[0] if it points
  901. * to constant __local_nameserver, or free it. */
  902. __nameserver = malloc(sizeof(__nameserver[0]));
  903. if (__nameserver)
  904. memcpy(__nameserver, &__local_nameserver, sizeof(__local_nameserver));
  905. else
  906. __nameserver = (void*) &__local_nameserver;
  907. __nameservers++;
  908. }
  909. if (__searchdomains == 0) {
  910. char buf[256];
  911. char *p;
  912. i = gethostname(buf, sizeof(buf) - 1);
  913. buf[sizeof(buf) - 1] = '\0';
  914. if (i == 0 && (p = strchr(buf, '.')) != NULL && p[1]) {
  915. p = strdup(p + 1);
  916. if (!p)
  917. goto err;
  918. __searchdomain = malloc(sizeof(__searchdomain[0]));
  919. if (!__searchdomain) {
  920. free(p);
  921. goto err;
  922. }
  923. __searchdomain[0] = p;
  924. __searchdomains++;
  925. err: ;
  926. }
  927. }
  928. DPRINTF("nameservers = %d\n", __nameservers);
  929. sync:
  930. if (__res_sync)
  931. __res_sync();
  932. }
  933. #endif
  934. #ifdef L_closenameservers
  935. /* Must be called under __resolv_lock. */
  936. void attribute_hidden __close_nameservers(void)
  937. {
  938. if (__nameserver != (void*) &__local_nameserver)
  939. free(__nameserver);
  940. __nameserver = NULL;
  941. __nameservers = 0;
  942. while (__searchdomains)
  943. free(__searchdomain[--__searchdomains]);
  944. free(__searchdomain);
  945. __searchdomain = NULL;
  946. /*__searchdomains = 0; - already is */
  947. }
  948. #endif
  949. #ifdef L_dnslookup
  950. /* On entry:
  951. * a.buf(len) = auxiliary buffer for IP addresses after first one
  952. * a.add_count = how many additional addresses are there already
  953. * outpacket = where to save ptr to raw packet? can be NULL
  954. * On exit:
  955. * ret < 0: error, all other data is not valid
  956. * a.add_count & a.buf: updated
  957. * a.rdlength: length of addresses (4 bytes for IPv4)
  958. * *outpacket: updated (packet is malloced, you need to free it)
  959. * a.rdata: points into *outpacket to 1st IP addr
  960. * NB: don't pass outpacket == NULL if you need to use a.rdata!
  961. * a.atype: type of query?
  962. * a.dotted: which name we _actually_ used. May contain search domains
  963. * appended. (why the filed is called "dotted" I have no idea)
  964. * This is a malloced string. May be NULL because strdup failed.
  965. */
  966. int attribute_hidden __dns_lookup(const char *name, int type,
  967. unsigned char **outpacket,
  968. struct resolv_answer *a)
  969. {
  970. /* Protected by __resolv_lock: */
  971. static int last_ns_num = 0;
  972. static uint16_t last_id = 1;
  973. int i, j, len, fd, pos, rc;
  974. int name_len;
  975. #ifdef USE_SELECT
  976. struct timeval tv;
  977. fd_set fds;
  978. #else
  979. struct pollfd fds;
  980. #endif
  981. struct resolv_header h;
  982. struct resolv_question q;
  983. struct resolv_answer ma;
  984. bool first_answer = 1;
  985. int retries_left;
  986. unsigned char *packet = malloc(PACKETSZ);
  987. char *lookup;
  988. int variant = -1; /* search domain to append, -1: none */
  989. int local_ns_num = -1; /* Nth server to use */
  990. int local_id = local_id; /* for compiler */
  991. int sdomains;
  992. bool ends_with_dot;
  993. sockaddr46_t sa;
  994. fd = -1;
  995. lookup = NULL;
  996. name_len = strlen(name);
  997. if ((unsigned)name_len >= MAXDNAME - MAXLEN_searchdomain - 2)
  998. goto fail; /* paranoia */
  999. lookup = malloc(name_len + 1/*for '.'*/ + MAXLEN_searchdomain + 1);
  1000. if (!packet || !lookup || !name[0])
  1001. goto fail;
  1002. ends_with_dot = (name[name_len - 1] == '.');
  1003. /* no strcpy! paranoia, user might change name[] under us */
  1004. memcpy(lookup, name, name_len);
  1005. DPRINTF("Looking up type %d answer for '%s'\n", type, name);
  1006. retries_left = 0; /* for compiler */
  1007. do {
  1008. unsigned reply_timeout;
  1009. if (fd != -1) {
  1010. close(fd);
  1011. fd = -1;
  1012. }
  1013. /* Mess with globals while under lock */
  1014. /* NB: even data *pointed to* by globals may vanish
  1015. * outside the locks. We should assume any and all
  1016. * globals can completely change between locked
  1017. * code regions. OTOH, this is rare, so we don't need
  1018. * to handle it "nicely" (do not skip servers,
  1019. * search domains, etc), we only need to ensure
  1020. * we do not SEGV, use freed+overwritten data
  1021. * or do other Really Bad Things. */
  1022. __UCLIBC_MUTEX_LOCK(__resolv_lock);
  1023. __open_nameservers();
  1024. sdomains = __searchdomains;
  1025. lookup[name_len] = '\0';
  1026. if ((unsigned)variant < sdomains) {
  1027. /* lookup is name_len + 1 + MAXLEN_searchdomain + 1 long */
  1028. /* __searchdomain[] is not bigger than MAXLEN_searchdomain */
  1029. lookup[name_len] = '.';
  1030. strcpy(&lookup[name_len + 1], __searchdomain[variant]);
  1031. }
  1032. /* first time? pick starting server etc */
  1033. if (local_ns_num < 0) {
  1034. local_id = last_id;
  1035. /*TODO: implement /etc/resolv.conf's "options rotate"
  1036. (a.k.a. RES_ROTATE bit in _res.options)
  1037. local_ns_num = 0;
  1038. if (_res.options & RES_ROTATE) */
  1039. local_ns_num = last_ns_num;
  1040. /*TODO: use _res.retry */
  1041. retries_left = __nameservers * RES_DFLRETRY;
  1042. }
  1043. retries_left--;
  1044. if (local_ns_num >= __nameservers)
  1045. local_ns_num = 0;
  1046. local_id++;
  1047. local_id &= 0xffff;
  1048. /* write new values back while still under lock */
  1049. last_id = local_id;
  1050. last_ns_num = local_ns_num;
  1051. /* struct copy */
  1052. /* can't just take a pointer, __nameserver[x]
  1053. * is not safe to use outside of locks */
  1054. sa = __nameserver[local_ns_num];
  1055. __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
  1056. memset(packet, 0, PACKETSZ);
  1057. memset(&h, 0, sizeof(h));
  1058. /* encode header */
  1059. h.id = local_id;
  1060. h.qdcount = 1;
  1061. h.rd = 1;
  1062. DPRINTF("encoding header\n", h.rd);
  1063. i = __encode_header(&h, packet, PACKETSZ);
  1064. if (i < 0)
  1065. goto fail;
  1066. /* encode question */
  1067. DPRINTF("lookup name: %s\n", lookup);
  1068. q.dotted = lookup;
  1069. q.qtype = type;
  1070. q.qclass = C_IN; /* CLASS_IN */
  1071. j = __encode_question(&q, packet+i, PACKETSZ-i);
  1072. if (j < 0)
  1073. goto fail;
  1074. len = i + j;
  1075. /* send packet */
  1076. DPRINTF("On try %d, sending query to port %d\n",
  1077. retries_left, NAMESERVER_PORT);
  1078. fd = socket(sa.sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
  1079. if (fd < 0) /* paranoia */
  1080. goto try_next_server;
  1081. rc = connect(fd, &sa.sa, sizeof(sa));
  1082. if (rc < 0) {
  1083. /*if (errno == ENETUNREACH) { */
  1084. /* routing error, presume not transient */
  1085. goto try_next_server;
  1086. /*} */
  1087. /*For example, what transient error this can be? Can't think of any */
  1088. /* retry */
  1089. /*continue; */
  1090. }
  1091. DPRINTF("Xmit packet len:%d id:%d qr:%d\n", len, h.id, h.qr);
  1092. /* no error check - if it fails, we time out on recv */
  1093. send(fd, packet, len, 0);
  1094. #ifdef USE_SELECT
  1095. /*TODO: use _res.retrans*/
  1096. reply_timeout = RES_TIMEOUT;
  1097. wait_again:
  1098. FD_ZERO(&fds);
  1099. FD_SET(fd, &fds);
  1100. tv.tv_sec = reply_timeout;
  1101. tv.tv_usec = 0;
  1102. if (select(fd + 1, &fds, NULL, NULL, &tv) <= 0) {
  1103. DPRINTF("Timeout\n");
  1104. /* timed out, so retry send and receive
  1105. * to next nameserver */
  1106. goto try_next_server;
  1107. }
  1108. reply_timeout--;
  1109. #else
  1110. reply_timeout = RES_TIMEOUT * 1000;
  1111. wait_again:
  1112. fds.fd = fd;
  1113. fds.events = POLLIN;
  1114. if (poll(&fds, 1, reply_timeout) <= 0) {
  1115. DPRINTF("Timeout\n");
  1116. /* timed out, so retry send and receive
  1117. * to next nameserver */
  1118. goto try_next_server;
  1119. }
  1120. /*TODO: better timeout accounting?*/
  1121. reply_timeout -= 1000;
  1122. #endif
  1123. len = recv(fd, packet, PACKETSZ, MSG_DONTWAIT);
  1124. if (len < HFIXEDSZ) {
  1125. /* too short!
  1126. * it's just a bogus packet from somewhere */
  1127. bogus_packet:
  1128. if (reply_timeout)
  1129. goto wait_again;
  1130. goto try_next_server;
  1131. }
  1132. __decode_header(packet, &h);
  1133. DPRINTF("id = %d, qr = %d\n", h.id, h.qr);
  1134. if (h.id != local_id || !h.qr) {
  1135. /* unsolicited */
  1136. goto bogus_packet;
  1137. }
  1138. DPRINTF("Got response (i think)!\n");
  1139. DPRINTF("qrcount=%d,ancount=%d,nscount=%d,arcount=%d\n",
  1140. h.qdcount, h.ancount, h.nscount, h.arcount);
  1141. DPRINTF("opcode=%d,aa=%d,tc=%d,rd=%d,ra=%d,rcode=%d\n",
  1142. h.opcode, h.aa, h.tc, h.rd, h.ra, h.rcode);
  1143. /* bug 660 says we treat negative response as an error
  1144. * and retry, which is, eh, an error. :)
  1145. * We were incurring long delays because of this. */
  1146. if (h.rcode == NXDOMAIN) {
  1147. /* if possible, try next search domain */
  1148. if (!ends_with_dot) {
  1149. DPRINTF("variant:%d sdomains:%d\n", variant, sdomains);
  1150. if (variant < sdomains - 1) {
  1151. /* next search domain */
  1152. variant++;
  1153. continue;
  1154. }
  1155. /* no more search domains to try */
  1156. }
  1157. /* dont loop, this is "no such host" situation */
  1158. h_errno = HOST_NOT_FOUND;
  1159. goto fail1;
  1160. }
  1161. /* Insert other non-fatal errors here, which do not warrant
  1162. * switching to next nameserver */
  1163. /* Strange error, assuming this nameserver is feeling bad */
  1164. if (h.rcode != 0)
  1165. goto try_next_server;
  1166. /* Code below won't work correctly with h.ancount == 0, so... */
  1167. if (h.ancount <= 0) {
  1168. h_errno = NO_DATA; /* is this correct code? */
  1169. goto fail1;
  1170. }
  1171. pos = HFIXEDSZ;
  1172. for (j = 0; j < h.qdcount; j++) {
  1173. DPRINTF("Skipping question %d at %d\n", j, pos);
  1174. /* returns -1 only if packet == NULL (can't happen) */
  1175. i = __length_question(packet, pos);
  1176. DPRINTF("Length of question %d is %d\n", j, i);
  1177. pos += i;
  1178. }
  1179. DPRINTF("Decoding answer at pos %d\n", pos);
  1180. first_answer = 1;
  1181. for (j = 0; j < h.ancount && pos < len; j++) {
  1182. i = __decode_answer(packet, pos, len, &ma);
  1183. if (i < 0) {
  1184. DPRINTF("failed decode %d\n", i);
  1185. /* If the message was truncated but we have
  1186. * decoded some answers, pretend it's OK */
  1187. if (j && h.tc)
  1188. break;
  1189. goto try_next_server;
  1190. }
  1191. pos += i;
  1192. if (first_answer) {
  1193. ma.buf = a->buf;
  1194. ma.buflen = a->buflen;
  1195. ma.add_count = a->add_count;
  1196. memcpy(a, &ma, sizeof(ma));
  1197. if (a->atype != T_SIG && (NULL == a->buf || (type != T_A && type != T_AAAA)))
  1198. break;
  1199. if (a->atype != type) {
  1200. free(a->dotted);
  1201. continue;
  1202. }
  1203. a->add_count = h.ancount - j - 1;
  1204. if ((a->rdlength + sizeof(struct in_addr*)) * a->add_count > a->buflen)
  1205. break;
  1206. a->add_count = 0;
  1207. first_answer = 0;
  1208. } else {
  1209. free(ma.dotted);
  1210. if (ma.atype != type)
  1211. continue;
  1212. if (a->rdlength != ma.rdlength) {
  1213. free(a->dotted);
  1214. DPRINTF("Answer address len(%u) differs from original(%u)\n",
  1215. ma.rdlength, a->rdlength);
  1216. goto try_next_server;
  1217. }
  1218. memcpy(a->buf + (a->add_count * ma.rdlength), ma.rdata, ma.rdlength);
  1219. ++a->add_count;
  1220. }
  1221. }
  1222. /* Success! */
  1223. DPRINTF("Answer name = |%s|\n", a->dotted);
  1224. DPRINTF("Answer type = |%d|\n", a->atype);
  1225. if (fd != -1)
  1226. close(fd);
  1227. if (outpacket)
  1228. *outpacket = packet;
  1229. else
  1230. free(packet);
  1231. free(lookup);
  1232. return len;
  1233. try_next_server:
  1234. /* Try next nameserver */
  1235. local_ns_num++;
  1236. variant = -1;
  1237. } while (retries_left > 0);
  1238. fail:
  1239. h_errno = NETDB_INTERNAL;
  1240. fail1:
  1241. if (fd != -1)
  1242. close(fd);
  1243. free(lookup);
  1244. free(packet);
  1245. return -1;
  1246. }
  1247. #endif
  1248. #ifdef L_read_etc_hosts_r
  1249. FILE * __open_etc_hosts(void)
  1250. {
  1251. FILE * fp;
  1252. if ((fp = fopen("/etc/hosts", "r")) == NULL) {
  1253. fp = fopen("/etc/config/hosts", "r");
  1254. }
  1255. return fp;
  1256. }
  1257. int attribute_hidden __read_etc_hosts_r(
  1258. FILE * fp,
  1259. const char * name,
  1260. int type,
  1261. enum etc_hosts_action action,
  1262. struct hostent * result_buf,
  1263. char * buf, size_t buflen,
  1264. struct hostent ** result,
  1265. int * h_errnop)
  1266. {
  1267. struct in_addr **addr_list = NULL;
  1268. struct in_addr *in = NULL;
  1269. char *cp, **alias;
  1270. int aliases, i, ret = HOST_NOT_FOUND;
  1271. *h_errnop = NETDB_INTERNAL;
  1272. /* make sure pointer is aligned */
  1273. i = ALIGN_BUFFER_OFFSET(buf);
  1274. buf += i;
  1275. buflen -= i;
  1276. /* Layout in buf:
  1277. * char *alias[ALIAS_DIM];
  1278. * struct in[6]_addr* addr_list[2];
  1279. * struct in[6]_addr* in;
  1280. * char line_buffer[80+];
  1281. */
  1282. #define in6 ((struct in6_addr *)in)
  1283. alias = (char **)buf;
  1284. buf += sizeof(char **) * ALIAS_DIM;
  1285. buflen -= sizeof(char **) * ALIAS_DIM;
  1286. if ((ssize_t)buflen < 0)
  1287. return ERANGE;
  1288. if (action != GETHOSTENT) {
  1289. addr_list = (struct in_addr**)buf;
  1290. buf += sizeof(*addr_list) * 2;
  1291. buflen -= sizeof(*addr_list) * 2;
  1292. in = (struct in_addr*)buf;
  1293. #ifndef __UCLIBC_HAS_IPV6__
  1294. buf += sizeof(*in);
  1295. buflen -= sizeof(*in);
  1296. #else
  1297. buf += sizeof(*in6);
  1298. buflen -= sizeof(*in6);
  1299. #endif
  1300. if ((ssize_t)buflen < 80)
  1301. return ERANGE;
  1302. fp = __open_etc_hosts();
  1303. if (fp == NULL) {
  1304. *result = NULL;
  1305. return errno;
  1306. }
  1307. addr_list[0] = in;
  1308. addr_list[1] = NULL;
  1309. }
  1310. *h_errnop = HOST_NOT_FOUND;
  1311. while (fgets(buf, buflen, fp)) {
  1312. *strchrnul(buf, '#') = '\0';
  1313. DPRINTF("Looking at: %s\n", buf);
  1314. aliases = 0;
  1315. cp = buf;
  1316. while (*cp) {
  1317. while (*cp && isspace(*cp))
  1318. *cp++ = '\0';
  1319. if (!*cp)
  1320. break;
  1321. if (aliases < (2 + MAX_ALIASES))
  1322. alias[aliases++] = cp;
  1323. while (*cp && !isspace(*cp))
  1324. cp++;
  1325. }
  1326. alias[aliases] = NULL;
  1327. if (aliases < 2)
  1328. continue; /* syntax error really */
  1329. if (action == GETHOSTENT) {
  1330. /* Return whatever the next entry happens to be. */
  1331. break;
  1332. }
  1333. if (action == GET_HOSTS_BYADDR) {
  1334. if (strcmp(name, alias[0]) != 0)
  1335. continue;
  1336. } else {
  1337. /* GET_HOSTS_BYNAME */
  1338. for (i = 1; i < aliases; i++)
  1339. if (strcasecmp(name, alias[i]) == 0)
  1340. goto found;
  1341. continue;
  1342. found: ;
  1343. }
  1344. if (0) /* nothing */;
  1345. #ifdef __UCLIBC_HAS_IPV4__
  1346. else if (type == AF_INET && inet_pton(AF_INET, alias[0], in) > 0) {
  1347. DPRINTF("Found INET\n");
  1348. result_buf->h_addrtype = AF_INET;
  1349. result_buf->h_length = sizeof(*in);
  1350. result_buf->h_name = alias[1];
  1351. result_buf->h_addr_list = (char**) addr_list;
  1352. result_buf->h_aliases = alias + 2;
  1353. *result = result_buf;
  1354. ret = NETDB_SUCCESS;
  1355. }
  1356. #endif
  1357. #ifdef __UCLIBC_HAS_IPV6__
  1358. else if (type == AF_INET6 && inet_pton(AF_INET6, alias[0], in6) > 0) {
  1359. DPRINTF("Found INET6\n");
  1360. result_buf->h_addrtype = AF_INET6;
  1361. result_buf->h_length = sizeof(*in6);
  1362. result_buf->h_name = alias[1];
  1363. result_buf->h_addr_list = (char**) addr_list;
  1364. result_buf->h_aliases = alias + 2;
  1365. *result = result_buf;
  1366. ret = NETDB_SUCCESS;
  1367. }
  1368. #endif
  1369. else {
  1370. /* continue parsing in the hope the user has multiple
  1371. * host types listed in the database like so:
  1372. * <ipv4 addr> host
  1373. * <ipv6 addr> host
  1374. * If looking for an IPv6 addr, don't bail when we got the IPv4
  1375. */
  1376. DPRINTF("Error: Found host but diff network type\n");
  1377. /* NB: gethostbyname2_r depends on this feature
  1378. * to avoid looking for IPv6 addr of "localhost" etc */
  1379. ret = TRY_AGAIN;
  1380. continue;
  1381. }
  1382. break;
  1383. }
  1384. if (action != GETHOSTENT)
  1385. fclose(fp);
  1386. return ret;
  1387. #undef in6
  1388. }
  1389. #endif
  1390. #ifdef L_get_hosts_byname_r
  1391. int attribute_hidden __get_hosts_byname_r(const char * name, int type,
  1392. struct hostent * result_buf,
  1393. char * buf, size_t buflen,
  1394. struct hostent ** result,
  1395. int * h_errnop)
  1396. {
  1397. return __read_etc_hosts_r(NULL, name, type, GET_HOSTS_BYNAME,
  1398. result_buf, buf, buflen, result, h_errnop);
  1399. }
  1400. #endif
  1401. #ifdef L_get_hosts_byaddr_r
  1402. int attribute_hidden __get_hosts_byaddr_r(const char * addr, int len, int type,
  1403. struct hostent * result_buf,
  1404. char * buf, size_t buflen,
  1405. struct hostent ** result,
  1406. int * h_errnop)
  1407. {
  1408. #ifndef __UCLIBC_HAS_IPV6__
  1409. char ipaddr[INET_ADDRSTRLEN];
  1410. #else
  1411. char ipaddr[INET6_ADDRSTRLEN];
  1412. #endif
  1413. switch (type) {
  1414. #ifdef __UCLIBC_HAS_IPV4__
  1415. case AF_INET:
  1416. if (len != sizeof(struct in_addr))
  1417. return 0;
  1418. break;
  1419. #endif
  1420. #ifdef __UCLIBC_HAS_IPV6__
  1421. case AF_INET6:
  1422. if (len != sizeof(struct in6_addr))
  1423. return 0;
  1424. break;
  1425. #endif
  1426. default:
  1427. return 0;
  1428. }
  1429. inet_ntop(type, addr, ipaddr, sizeof(ipaddr));
  1430. return __read_etc_hosts_r(NULL, ipaddr, type, GET_HOSTS_BYADDR,
  1431. result_buf, buf, buflen, result, h_errnop);
  1432. }
  1433. #endif
  1434. #ifdef L_getnameinfo
  1435. int getnameinfo(const struct sockaddr *sa, socklen_t addrlen, char *host,
  1436. socklen_t hostlen, char *serv, socklen_t servlen,
  1437. unsigned int flags)
  1438. {
  1439. int serrno = errno;
  1440. unsigned ok;
  1441. struct hostent *h = NULL;
  1442. char domain[256];
  1443. if (flags & ~(NI_NUMERICHOST|NI_NUMERICSERV|NI_NOFQDN|NI_NAMEREQD|NI_DGRAM))
  1444. return EAI_BADFLAGS;
  1445. if (sa == NULL || addrlen < sizeof(sa_family_t))
  1446. return EAI_FAMILY;
  1447. ok = sa->sa_family;
  1448. if (ok == AF_LOCAL) /* valid */;
  1449. #ifdef __UCLIBC_HAS_IPV4__
  1450. else if (ok == AF_INET) {
  1451. if (addrlen < sizeof(struct sockaddr_in))
  1452. return EAI_FAMILY;
  1453. }
  1454. #endif
  1455. #ifdef __UCLIBC_HAS_IPV6__
  1456. else if (ok == AF_INET6) {
  1457. if (addrlen < sizeof(struct sockaddr_in6))
  1458. return EAI_FAMILY;
  1459. }
  1460. #endif
  1461. else
  1462. return EAI_FAMILY;
  1463. ok = 0;
  1464. if (host != NULL && hostlen > 0)
  1465. switch (sa->sa_family) {
  1466. case AF_INET:
  1467. #ifdef __UCLIBC_HAS_IPV6__
  1468. case AF_INET6:
  1469. #endif
  1470. if (!(flags & NI_NUMERICHOST)) {
  1471. if (0) /* nothing */;
  1472. #ifdef __UCLIBC_HAS_IPV6__
  1473. else if (sa->sa_family == AF_INET6)
  1474. h = gethostbyaddr((const void *)
  1475. &(((const struct sockaddr_in6 *) sa)->sin6_addr),
  1476. sizeof(struct in6_addr), AF_INET6);
  1477. #endif
  1478. #ifdef __UCLIBC_HAS_IPV4__
  1479. else
  1480. h = gethostbyaddr((const void *)
  1481. &(((const struct sockaddr_in *)sa)->sin_addr),
  1482. sizeof(struct in_addr), AF_INET);
  1483. #endif
  1484. if (h) {
  1485. char *c;
  1486. #undef min
  1487. #define min(x,y) (((x) > (y)) ? (y) : (x))
  1488. if ((flags & NI_NOFQDN)
  1489. && (getdomainname(domain, sizeof(domain)) == 0)
  1490. && (c = strstr(h->h_name, domain)) != NULL
  1491. && (c != h->h_name) && (*(--c) == '.')
  1492. ) {
  1493. strncpy(host, h->h_name,
  1494. min(hostlen, (size_t) (c - h->h_name)));
  1495. host[min(hostlen - 1, (size_t) (c - h->h_name))] = '\0';
  1496. } else {
  1497. strncpy(host, h->h_name, hostlen);
  1498. }
  1499. ok = 1;
  1500. #undef min
  1501. }
  1502. }
  1503. if (!ok) {
  1504. const char *c = NULL;
  1505. if (flags & NI_NAMEREQD) {
  1506. errno = serrno;
  1507. return EAI_NONAME;
  1508. }
  1509. if (0) /* nothing */;
  1510. #ifdef __UCLIBC_HAS_IPV6__
  1511. else if (sa->sa_family == AF_INET6) {
  1512. const struct sockaddr_in6 *sin6p;
  1513. sin6p = (const struct sockaddr_in6 *) sa;
  1514. c = inet_ntop(AF_INET6,
  1515. (const void *) &sin6p->sin6_addr,
  1516. host, hostlen);
  1517. #if 0
  1518. /* Does scope id need to be supported? */
  1519. uint32_t scopeid;
  1520. scopeid = sin6p->sin6_scope_id;
  1521. if (scopeid != 0) {
  1522. /* Buffer is >= IFNAMSIZ+1. */
  1523. char scopebuf[IFNAMSIZ + 1];
  1524. char *scopeptr;
  1525. int ni_numericscope = 0;
  1526. size_t real_hostlen = strnlen(host, hostlen);
  1527. size_t scopelen = 0;
  1528. scopebuf[0] = SCOPE_DELIMITER;
  1529. scopebuf[1] = '\0';
  1530. scopeptr = &scopebuf[1];
  1531. if (IN6_IS_ADDR_LINKLOCAL(&sin6p->sin6_addr)
  1532. || IN6_IS_ADDR_MC_LINKLOCAL(&sin6p->sin6_addr)) {
  1533. if (if_indextoname(scopeid, scopeptr) == NULL)
  1534. ++ni_numericscope;
  1535. else
  1536. scopelen = strlen(scopebuf);
  1537. } else {
  1538. ++ni_numericscope;
  1539. }
  1540. if (ni_numericscope)
  1541. scopelen = 1 + snprintf(scopeptr,
  1542. (scopebuf
  1543. + sizeof scopebuf
  1544. - scopeptr),
  1545. "%u", scopeid);
  1546. if (real_hostlen + scopelen + 1 > hostlen)
  1547. return EAI_SYSTEM;
  1548. memcpy(host + real_hostlen, scopebuf, scopelen + 1);
  1549. }
  1550. #endif
  1551. }
  1552. #endif /* __UCLIBC_HAS_IPV6__ */
  1553. #if defined __UCLIBC_HAS_IPV4__
  1554. else {
  1555. c = inet_ntop(AF_INET, (const void *)
  1556. &(((const struct sockaddr_in *) sa)->sin_addr),
  1557. host, hostlen);
  1558. }
  1559. #endif
  1560. if (c == NULL) {
  1561. errno = serrno;
  1562. return EAI_SYSTEM;
  1563. }
  1564. ok = 1;
  1565. }
  1566. break;
  1567. case AF_LOCAL:
  1568. if (!(flags & NI_NUMERICHOST)) {
  1569. struct utsname utsname;
  1570. if (!uname(&utsname)) {
  1571. strncpy(host, utsname.nodename, hostlen);
  1572. break;
  1573. };
  1574. };
  1575. if (flags & NI_NAMEREQD) {
  1576. errno = serrno;
  1577. return EAI_NONAME;
  1578. }
  1579. strncpy(host, "localhost", hostlen);
  1580. break;
  1581. /* Already checked above
  1582. default:
  1583. return EAI_FAMILY;
  1584. */
  1585. }
  1586. if (serv && (servlen > 0)) {
  1587. if (sa->sa_family == AF_LOCAL) {
  1588. strncpy(serv, ((const struct sockaddr_un *) sa)->sun_path, servlen);
  1589. } else { /* AF_INET || AF_INET6 */
  1590. if (!(flags & NI_NUMERICSERV)) {
  1591. struct servent *s;
  1592. s = getservbyport(((const struct sockaddr_in *) sa)->sin_port,
  1593. ((flags & NI_DGRAM) ? "udp" : "tcp"));
  1594. if (s) {
  1595. strncpy(serv, s->s_name, servlen);
  1596. goto DONE;
  1597. }
  1598. }
  1599. snprintf(serv, servlen, "%d",
  1600. ntohs(((const struct sockaddr_in *) sa)->sin_port));
  1601. }
  1602. }
  1603. DONE:
  1604. if (host && (hostlen > 0))
  1605. host[hostlen-1] = 0;
  1606. if (serv && (servlen > 0))
  1607. serv[servlen-1] = 0;
  1608. errno = serrno;
  1609. return 0;
  1610. }
  1611. libc_hidden_def(getnameinfo)
  1612. #endif
  1613. #ifdef L_gethostbyname_r
  1614. /* Bug 671 says:
  1615. * "uClibc resolver's gethostbyname does not return the requested name
  1616. * as an alias, but instead returns the canonical name. glibc's
  1617. * gethostbyname has a similar bug where it returns the requested name
  1618. * with the search domain name appended (to make a FQDN) as an alias,
  1619. * but not the original name itself. Both contradict POSIX, which says
  1620. * that the name argument passed to gethostbyname must be in the alias list"
  1621. * This is fixed now, and we differ from glibc:
  1622. *
  1623. * $ ./gethostbyname_uclibc wer.google.com
  1624. * h_name:'c13-ss-2-lb.cnet.com'
  1625. * h_length:4
  1626. * h_addrtype:2 AF_INET
  1627. * alias:'wer.google.com' <===
  1628. * addr: 0x4174efd8 '216.239.116.65'
  1629. *
  1630. * $ ./gethostbyname_glibc wer.google.com
  1631. * h_name:'c13-ss-2-lb.cnet.com'
  1632. * h_length:4
  1633. * h_addrtype:2 AF_INET
  1634. * alias:'wer.google.com.com' <===
  1635. * addr:'216.239.116.65'
  1636. *
  1637. * When examples were run, /etc/resolv.conf contained "search com" line.
  1638. */
  1639. int gethostbyname_r(const char * name,
  1640. struct hostent * result_buf,
  1641. char * buf,
  1642. size_t buflen,
  1643. struct hostent ** result,
  1644. int * h_errnop)
  1645. {
  1646. struct in_addr **addr_list;
  1647. char **alias;
  1648. char *alias0;
  1649. unsigned char *packet;
  1650. struct resolv_answer a;
  1651. int i;
  1652. int wrong_af = 0;
  1653. *result = NULL;
  1654. if (!name)
  1655. return EINVAL;
  1656. /* do /etc/hosts first */
  1657. {
  1658. int old_errno = errno; /* save the old errno and reset errno */
  1659. __set_errno(0); /* to check for missing /etc/hosts. */
  1660. i = __get_hosts_byname_r(name, AF_INET, result_buf,
  1661. buf, buflen, result, h_errnop);
  1662. if (i == NETDB_SUCCESS) {
  1663. __set_errno(old_errno);
  1664. return i;
  1665. }
  1666. switch (*h_errnop) {
  1667. case HOST_NOT_FOUND:
  1668. wrong_af = (i == TRY_AGAIN);
  1669. case NO_ADDRESS:
  1670. break;
  1671. case NETDB_INTERNAL:
  1672. if (errno == ENOENT) {
  1673. break;
  1674. }
  1675. /* else fall through */
  1676. default:
  1677. return i;
  1678. }
  1679. __set_errno(old_errno);
  1680. }
  1681. DPRINTF("Nothing found in /etc/hosts\n");
  1682. *h_errnop = NETDB_INTERNAL;
  1683. /* prepare future h_aliases[0] */
  1684. i = strlen(name) + 1;
  1685. if ((ssize_t)buflen <= i)
  1686. return ERANGE;
  1687. memcpy(buf, name, i); /* paranoia: name might change */
  1688. alias0 = buf;
  1689. buf += i;
  1690. buflen -= i;
  1691. /* make sure pointer is aligned */
  1692. i = ALIGN_BUFFER_OFFSET(buf);
  1693. buf += i;
  1694. buflen -= i;
  1695. /* Layout in buf:
  1696. * char *alias[2];
  1697. * struct in_addr* addr_list[NN+1];
  1698. * struct in_addr* in[NN];
  1699. */
  1700. alias = (char **)buf;
  1701. buf += sizeof(alias[0]) * 2;
  1702. buflen -= sizeof(alias[0]) * 2;
  1703. addr_list = (struct in_addr **)buf;
  1704. /* buflen may be < 0, must do signed compare */
  1705. if ((ssize_t)buflen < 256)
  1706. return ERANGE;
  1707. /* we store only one "alias" - the name itself */
  1708. #ifdef __UCLIBC_MJN3_ONLY__
  1709. #warning TODO -- generate the full list
  1710. #endif
  1711. alias[0] = alias0;
  1712. alias[1] = NULL;
  1713. /* maybe it is already an address? */
  1714. {
  1715. struct in_addr *in = (struct in_addr *)(buf + sizeof(addr_list[0]) * 2);
  1716. if (inet_aton(name, in)) {
  1717. addr_list[0] = in;
  1718. addr_list[1] = NULL;
  1719. result_buf->h_name = alias0;
  1720. result_buf->h_aliases = alias;
  1721. result_buf->h_addrtype = AF_INET;
  1722. result_buf->h_length = sizeof(struct in_addr);
  1723. result_buf->h_addr_list = (char **) addr_list;
  1724. *result = result_buf;
  1725. *h_errnop = NETDB_SUCCESS;
  1726. return NETDB_SUCCESS;
  1727. }
  1728. }
  1729. /* what if /etc/hosts has it but it's not IPv4?
  1730. * F.e. "::1 localhost6". We don't do DNS query for such hosts -
  1731. * "ping localhost6" should be fast even if DNS server is down! */
  1732. if (wrong_af) {
  1733. *h_errnop = HOST_NOT_FOUND;
  1734. return TRY_AGAIN;
  1735. }
  1736. /* talk to DNS servers */
  1737. a.buf = buf;
  1738. /* take into account that at least one address will be there,
  1739. * we'll need space of one in_addr + two addr_list[] elems */
  1740. a.buflen = buflen - ((sizeof(addr_list[0]) * 2 + sizeof(struct in_addr)));
  1741. a.add_count = 0;
  1742. i = __dns_lookup(name, T_A, &packet, &a);
  1743. if (i < 0) {
  1744. *h_errnop = HOST_NOT_FOUND;
  1745. DPRINTF("__dns_lookup returned < 0\n");
  1746. return TRY_AGAIN;
  1747. }
  1748. if (a.atype == T_A) { /* ADDRESS */
  1749. /* we need space for addr_list[] and one IPv4 address */
  1750. /* + 1 accounting for 1st addr (it's in a.rdata),
  1751. * another + 1 for NULL in last addr_list[]: */
  1752. int need_bytes = sizeof(addr_list[0]) * (a.add_count + 1 + 1)
  1753. /* for 1st addr (it's in a.rdata): */
  1754. + sizeof(struct in_addr);
  1755. /* how many bytes will 2nd and following addresses take? */
  1756. int ips_len = a.add_count * a.rdlength;
  1757. buflen -= (need_bytes + ips_len);
  1758. if ((ssize_t)buflen < 0) {
  1759. DPRINTF("buffer too small for all addresses\n");
  1760. /* *h_errnop = NETDB_INTERNAL; - already is */
  1761. i = ERANGE;
  1762. goto free_and_ret;
  1763. }
  1764. /* if there are additional addresses in buf,
  1765. * move them forward so that they are not destroyed */
  1766. DPRINTF("a.add_count:%d a.rdlength:%d a.rdata:%p\n", a.add_count, a.rdlength, a.rdata);
  1767. memmove(buf + need_bytes, buf, ips_len);
  1768. /* 1st address is in a.rdata, insert it */
  1769. buf += need_bytes - sizeof(struct in_addr);
  1770. memcpy(buf, a.rdata, sizeof(struct in_addr));
  1771. /* fill addr_list[] */
  1772. for (i = 0; i <= a.add_count; i++) {
  1773. addr_list[i] = (struct in_addr*)buf;
  1774. buf += sizeof(struct in_addr);
  1775. }
  1776. addr_list[i] = NULL;
  1777. /* if we have enough space, we can report "better" name
  1778. * (it may contain search domains attached by __dns_lookup,
  1779. * or CNAME of the host if it is different from the name
  1780. * we used to find it) */
  1781. if (a.dotted && buflen > strlen(a.dotted)) {
  1782. strcpy(buf, a.dotted);
  1783. alias0 = buf;
  1784. }
  1785. result_buf->h_name = alias0;
  1786. result_buf->h_aliases = alias;
  1787. result_buf->h_addrtype = AF_INET;
  1788. result_buf->h_length = sizeof(struct in_addr);
  1789. result_buf->h_addr_list = (char **) addr_list;
  1790. *result = result_buf;
  1791. *h_errnop = NETDB_SUCCESS;
  1792. i = NETDB_SUCCESS;
  1793. goto free_and_ret;
  1794. }
  1795. *h_errnop = HOST_NOT_FOUND;
  1796. i = TRY_AGAIN;
  1797. free_and_ret:
  1798. free(a.dotted);
  1799. free(packet);
  1800. return i;
  1801. }
  1802. libc_hidden_def(gethostbyname_r)
  1803. #endif
  1804. #ifdef L_gethostbyname2_r
  1805. int gethostbyname2_r(const char *name,
  1806. int family,
  1807. struct hostent * result_buf,
  1808. char * buf,
  1809. size_t buflen,
  1810. struct hostent ** result,
  1811. int * h_errnop)
  1812. {
  1813. #ifndef __UCLIBC_HAS_IPV6__
  1814. return family == (AF_INET)
  1815. ? gethostbyname_r(name, result_buf, buf, buflen, result, h_errnop)
  1816. : HOST_NOT_FOUND;
  1817. #else
  1818. struct in6_addr *in;
  1819. struct in6_addr **addr_list;
  1820. unsigned char *packet;
  1821. struct resolv_answer a;
  1822. int i;
  1823. int nest = 0;
  1824. int wrong_af = 0;
  1825. if (family == AF_INET)
  1826. return gethostbyname_r(name, result_buf, buf, buflen, result, h_errnop);
  1827. *result = NULL;
  1828. if (family != AF_INET6)
  1829. return EINVAL;
  1830. if (!name)
  1831. return EINVAL;
  1832. /* do /etc/hosts first */
  1833. {
  1834. int old_errno = errno; /* Save the old errno and reset errno */
  1835. __set_errno(0); /* to check for missing /etc/hosts. */
  1836. i = __get_hosts_byname_r(name, AF_INET6 /*family*/, result_buf,
  1837. buf, buflen, result, h_errnop);
  1838. if (i == NETDB_SUCCESS) {
  1839. __set_errno(old_errno);
  1840. return i;
  1841. }
  1842. switch (*h_errnop) {
  1843. case HOST_NOT_FOUND:
  1844. wrong_af = (i == TRY_AGAIN);
  1845. case NO_ADDRESS:
  1846. break;
  1847. case NETDB_INTERNAL:
  1848. if (errno == ENOENT) {
  1849. break;
  1850. }
  1851. /* else fall through */
  1852. default:
  1853. return i;
  1854. }
  1855. __set_errno(old_errno);
  1856. }
  1857. DPRINTF("Nothing found in /etc/hosts\n");
  1858. *h_errnop = NETDB_INTERNAL;
  1859. /* make sure pointer is aligned */
  1860. i = ALIGN_BUFFER_OFFSET(buf);
  1861. buf += i;
  1862. buflen -= i;
  1863. /* Layout in buf:
  1864. * struct in6_addr* in;
  1865. * struct in6_addr* addr_list[2];
  1866. * char scratch_buf[256];
  1867. */
  1868. in = (struct in6_addr*)buf;
  1869. buf += sizeof(*in);
  1870. buflen -= sizeof(*in);
  1871. addr_list = (struct in6_addr**)buf;
  1872. buf += sizeof(*addr_list) * 2;
  1873. buflen -= sizeof(*addr_list) * 2;
  1874. if ((ssize_t)buflen < 256)
  1875. return ERANGE;
  1876. addr_list[0] = in;
  1877. addr_list[1] = NULL;
  1878. strncpy(buf, name, buflen);
  1879. buf[buflen] = '\0';
  1880. /* maybe it is already an address? */
  1881. if (inet_pton(AF_INET6, name, in)) {
  1882. result_buf->h_name = buf;
  1883. result_buf->h_addrtype = AF_INET6;
  1884. result_buf->h_length = sizeof(*in);
  1885. result_buf->h_addr_list = (char **) addr_list;
  1886. /* result_buf->h_aliases = ??? */
  1887. *result = result_buf;
  1888. *h_errnop = NETDB_SUCCESS;
  1889. return NETDB_SUCCESS;
  1890. }
  1891. /* what if /etc/hosts has it but it's not IPv6?
  1892. * F.e. "127.0.0.1 localhost". We don't do DNS query for such hosts -
  1893. * "ping localhost" should be fast even if DNS server is down! */
  1894. if (wrong_af) {
  1895. *h_errnop = HOST_NOT_FOUND;
  1896. return TRY_AGAIN;
  1897. }
  1898. /* talk to DNS servers */
  1899. /* TODO: why it's so different from gethostbyname_r (IPv4 case)? */
  1900. memset(&a, '\0', sizeof(a));
  1901. for (;;) {
  1902. /* Hmm why we memset(a) to zeros only once? */
  1903. i = __dns_lookup(buf, T_AAAA, &packet, &a);
  1904. if (i < 0) {
  1905. *h_errnop = HOST_NOT_FOUND;
  1906. return TRY_AGAIN;
  1907. }
  1908. strncpy(buf, a.dotted, buflen);
  1909. free(a.dotted);
  1910. if (a.atype != T_CNAME)
  1911. break;
  1912. DPRINTF("Got a CNAME in gethostbyname()\n");
  1913. if (++nest > MAX_RECURSE) {
  1914. *h_errnop = NO_RECOVERY;
  1915. return -1;
  1916. }
  1917. i = __decode_dotted(packet, a.rdoffset, buf, buflen);
  1918. free(packet);
  1919. if (i < 0) {
  1920. *h_errnop = NO_RECOVERY;
  1921. return -1;
  1922. }
  1923. }
  1924. if (a.atype == T_AAAA) { /* ADDRESS */
  1925. memcpy(in, a.rdata, sizeof(*in));
  1926. result_buf->h_name = buf;
  1927. result_buf->h_addrtype = AF_INET6;
  1928. result_buf->h_length = sizeof(*in);
  1929. result_buf->h_addr_list = (char **) addr_list;
  1930. /* result_buf->h_aliases = ??? */
  1931. free(packet);
  1932. *result = result_buf;
  1933. *h_errnop = NETDB_SUCCESS;
  1934. return NETDB_SUCCESS;
  1935. }
  1936. free(packet);
  1937. *h_errnop = HOST_NOT_FOUND;
  1938. return TRY_AGAIN;
  1939. #endif /* __UCLIBC_HAS_IPV6__ */
  1940. }
  1941. libc_hidden_def(gethostbyname2_r)
  1942. #endif
  1943. #ifdef L_gethostbyaddr_r
  1944. int gethostbyaddr_r(const void *addr, socklen_t addrlen, int type,
  1945. struct hostent * result_buf,
  1946. char * buf, size_t buflen,
  1947. struct hostent ** result,
  1948. int * h_errnop)
  1949. {
  1950. struct in_addr *in;
  1951. struct in_addr **addr_list;
  1952. char **alias;
  1953. unsigned char *packet;
  1954. struct resolv_answer a;
  1955. int i;
  1956. int nest = 0;
  1957. *result = NULL;
  1958. if (!addr)
  1959. return EINVAL;
  1960. switch (type) {
  1961. #ifdef __UCLIBC_HAS_IPV4__
  1962. case AF_INET:
  1963. if (addrlen != sizeof(struct in_addr))
  1964. return EINVAL;
  1965. break;
  1966. #endif
  1967. #ifdef __UCLIBC_HAS_IPV6__
  1968. case AF_INET6:
  1969. if (addrlen != sizeof(struct in6_addr))
  1970. return EINVAL;
  1971. break;
  1972. #endif
  1973. default:
  1974. return EINVAL;
  1975. }
  1976. /* do /etc/hosts first */
  1977. i = __get_hosts_byaddr_r(addr, addrlen, type, result_buf,
  1978. buf, buflen, result, h_errnop);
  1979. if (i == 0)
  1980. return i;
  1981. switch (*h_errnop) {
  1982. case HOST_NOT_FOUND:
  1983. case NO_ADDRESS:
  1984. break;
  1985. default:
  1986. return i;
  1987. }
  1988. *h_errnop = NETDB_INTERNAL;
  1989. /* make sure pointer is aligned */
  1990. i = ALIGN_BUFFER_OFFSET(buf);
  1991. buf += i;
  1992. buflen -= i;
  1993. /* Layout in buf:
  1994. * char *alias[ALIAS_DIM];
  1995. * struct in[6]_addr* addr_list[2];
  1996. * struct in[6]_addr* in;
  1997. * char scratch_buffer[256+];
  1998. */
  1999. #define in6 ((struct in6_addr *)in)
  2000. alias = (char **)buf;
  2001. buf += sizeof(*alias) * ALIAS_DIM;
  2002. buflen -= sizeof(*alias) * ALIAS_DIM;
  2003. addr_list = (struct in_addr**)buf;
  2004. buf += sizeof(*addr_list) * 2;
  2005. buflen -= sizeof(*addr_list) * 2;
  2006. in = (struct in_addr*)buf;
  2007. #ifndef __UCLIBC_HAS_IPV6__
  2008. buf += sizeof(*in);
  2009. buflen -= sizeof(*in);
  2010. #else
  2011. buf += sizeof(*in6);
  2012. buflen -= sizeof(*in6);
  2013. #endif
  2014. if ((ssize_t)buflen < 256)
  2015. return ERANGE;
  2016. alias[0] = buf;
  2017. alias[1] = NULL;
  2018. addr_list[0] = in;
  2019. addr_list[1] = NULL;
  2020. memcpy(&in, addr, addrlen);
  2021. if (0) /* nothing */;
  2022. #ifdef __UCLIBC_HAS_IPV4__
  2023. else IF_HAS_BOTH(if (type == AF_INET)) {
  2024. unsigned char *tp = (unsigned char *)addr;
  2025. sprintf(buf, "%u.%u.%u.%u.in-addr.arpa",
  2026. tp[3], tp[2], tp[1], tp[0]);
  2027. }
  2028. #endif
  2029. #ifdef __UCLIBC_HAS_IPV6__
  2030. else {
  2031. char *dst = buf;
  2032. unsigned char *tp = (unsigned char *)addr + addrlen - 1;
  2033. do {
  2034. dst += sprintf(dst, "%x.%x.", tp[i] & 0xf, tp[i] >> 4);
  2035. tp--;
  2036. } while (tp >= (unsigned char *)addr);
  2037. strcpy(dst, "ip6.arpa");
  2038. }
  2039. #endif
  2040. memset(&a, '\0', sizeof(a));
  2041. for (;;) {
  2042. /* Hmm why we memset(a) to zeros only once? */
  2043. i = __dns_lookup(buf, T_PTR, &packet, &a);
  2044. if (i < 0) {
  2045. *h_errnop = HOST_NOT_FOUND;
  2046. return TRY_AGAIN;
  2047. }
  2048. strncpy(buf, a.dotted, buflen);
  2049. free(a.dotted);
  2050. if (a.atype != T_CNAME)
  2051. break;
  2052. DPRINTF("Got a CNAME in gethostbyaddr()\n");
  2053. if (++nest > MAX_RECURSE) {
  2054. *h_errnop = NO_RECOVERY;
  2055. return -1;
  2056. }
  2057. /* Decode CNAME into buf, feed it to __dns_lookup() again */
  2058. i = __decode_dotted(packet, a.rdoffset, buf, buflen);
  2059. free(packet);
  2060. if (i < 0) {
  2061. *h_errnop = NO_RECOVERY;
  2062. return -1;
  2063. }
  2064. }
  2065. if (a.atype == T_PTR) { /* ADDRESS */
  2066. i = __decode_dotted(packet, a.rdoffset, buf, buflen);
  2067. free(packet);
  2068. result_buf->h_name = buf;
  2069. result_buf->h_addrtype = type;
  2070. result_buf->h_length = addrlen;
  2071. result_buf->h_addr_list = (char **) addr_list;
  2072. result_buf->h_aliases = alias;
  2073. *result = result_buf;
  2074. *h_errnop = NETDB_SUCCESS;
  2075. return NETDB_SUCCESS;
  2076. }
  2077. free(packet);
  2078. *h_errnop = NO_ADDRESS;
  2079. return TRY_AGAIN;
  2080. #undef in6
  2081. }
  2082. libc_hidden_def(gethostbyaddr_r)
  2083. #endif
  2084. #ifdef L_gethostent_r
  2085. __UCLIBC_MUTEX_STATIC(mylock, PTHREAD_MUTEX_INITIALIZER);
  2086. static smallint __stay_open;
  2087. static FILE * __gethostent_fp;
  2088. void endhostent(void)
  2089. {
  2090. __UCLIBC_MUTEX_LOCK(mylock);
  2091. __stay_open = 0;
  2092. if (__gethostent_fp) {
  2093. fclose(__gethostent_fp);
  2094. __gethostent_fp = NULL;
  2095. }
  2096. __UCLIBC_MUTEX_UNLOCK(mylock);
  2097. }
  2098. void sethostent(int stay_open)
  2099. {
  2100. __UCLIBC_MUTEX_LOCK(mylock);
  2101. __stay_open = (stay_open != 0);
  2102. __UCLIBC_MUTEX_UNLOCK(mylock);
  2103. }
  2104. int gethostent_r(struct hostent *result_buf, char *buf, size_t buflen,
  2105. struct hostent **result, int *h_errnop)
  2106. {
  2107. int ret;
  2108. __UCLIBC_MUTEX_LOCK(mylock);
  2109. if (__gethostent_fp == NULL) {
  2110. __gethostent_fp = __open_etc_hosts();
  2111. if (__gethostent_fp == NULL) {
  2112. *result = NULL;
  2113. ret = TRY_AGAIN;
  2114. goto DONE;
  2115. }
  2116. }
  2117. ret = __read_etc_hosts_r(__gethostent_fp, NULL, AF_INET, GETHOSTENT,
  2118. result_buf, buf, buflen, result, h_errnop);
  2119. if (__stay_open == 0) {
  2120. fclose(__gethostent_fp);
  2121. __gethostent_fp = NULL;
  2122. }
  2123. DONE:
  2124. __UCLIBC_MUTEX_UNLOCK(mylock);
  2125. return ret;
  2126. }
  2127. libc_hidden_def(gethostent_r)
  2128. #endif
  2129. #ifdef L_gethostent
  2130. struct hostent *gethostent(void)
  2131. {
  2132. static struct hostent h;
  2133. static char buf[
  2134. #ifndef __UCLIBC_HAS_IPV6__
  2135. sizeof(struct in_addr) + sizeof(struct in_addr *) * 2 +
  2136. #else
  2137. sizeof(struct in6_addr) + sizeof(struct in6_addr *) * 2 +
  2138. #endif /* __UCLIBC_HAS_IPV6__ */
  2139. sizeof(char *) * ALIAS_DIM +
  2140. 80 /*namebuffer*/ + 2 /* margin */];
  2141. struct hostent *host;
  2142. gethostent_r(&h, buf, sizeof(buf), &host, &h_errno);
  2143. return host;
  2144. }
  2145. #endif
  2146. #ifdef L_gethostbyname2
  2147. struct hostent *gethostbyname2(const char *name, int family)
  2148. {
  2149. #ifndef __UCLIBC_HAS_IPV6__
  2150. return family == AF_INET ? gethostbyname(name) : (struct hostent*)NULL;
  2151. #else
  2152. static struct hostent h;
  2153. static char buf[sizeof(struct in6_addr) +
  2154. sizeof(struct in6_addr *) * 2 +
  2155. sizeof(char *)*ALIAS_DIM + 384/*namebuffer*/ + 32/* margin */];
  2156. struct hostent *hp;
  2157. gethostbyname2_r(name, family, &h, buf, sizeof(buf), &hp, &h_errno);
  2158. return hp;
  2159. #endif
  2160. }
  2161. libc_hidden_def(gethostbyname2)
  2162. #endif
  2163. #ifdef L_gethostbyname
  2164. struct hostent *gethostbyname(const char *name)
  2165. {
  2166. #ifndef __UCLIBC_HAS_IPV6__
  2167. static struct hostent h;
  2168. static char buf[sizeof(struct in_addr) +
  2169. sizeof(struct in_addr *) * 2 +
  2170. sizeof(char *)*ALIAS_DIM + 384/*namebuffer*/ + 32/* margin */];
  2171. struct hostent *hp;
  2172. gethostbyname_r(name, &h, buf, sizeof(buf), &hp, &h_errno);
  2173. return hp;
  2174. #else
  2175. return gethostbyname2(name, AF_INET);
  2176. #endif
  2177. }
  2178. libc_hidden_def(gethostbyname)
  2179. #endif
  2180. #ifdef L_gethostbyaddr
  2181. struct hostent *gethostbyaddr(const void *addr, socklen_t len, int type)
  2182. {
  2183. static struct hostent h;
  2184. static char buf[
  2185. #ifndef __UCLIBC_HAS_IPV6__
  2186. sizeof(struct in_addr) + sizeof(struct in_addr *)*2 +
  2187. #else
  2188. sizeof(struct in6_addr) + sizeof(struct in6_addr *)*2 +
  2189. #endif /* __UCLIBC_HAS_IPV6__ */
  2190. sizeof(char *)*ALIAS_DIM + 384 /*namebuffer*/ + 32 /* margin */];
  2191. struct hostent *hp;
  2192. gethostbyaddr_r(addr, len, type, &h, buf, sizeof(buf), &hp, &h_errno);
  2193. return hp;
  2194. }
  2195. libc_hidden_def(gethostbyaddr)
  2196. #endif
  2197. #ifdef L_res_comp
  2198. /*
  2199. * Expand compressed domain name 'comp_dn' to full domain name.
  2200. * 'msg' is a pointer to the begining of the message,
  2201. * 'eomorig' points to the first location after the message,
  2202. * 'exp_dn' is a pointer to a buffer of size 'length' for the result.
  2203. * Return size of compressed name or -1 if there was an error.
  2204. */
  2205. int __dn_expand(const u_char *msg, const u_char *eom, const u_char *src,
  2206. char *dst, int dstsiz)
  2207. {
  2208. int n = ns_name_uncompress(msg, eom, src, dst, (size_t)dstsiz);
  2209. if (n > 0 && dst[0] == '.')
  2210. dst[0] = '\0';
  2211. return n;
  2212. }
  2213. #endif /* L_res_comp */
  2214. #ifdef L_ns_name
  2215. /* Thinking in noninternationalized USASCII (per the DNS spec),
  2216. * is this character visible and not a space when printed ?
  2217. */
  2218. static int printable(int ch)
  2219. {
  2220. return (ch > 0x20 && ch < 0x7f);
  2221. }
  2222. /* Thinking in noninternationalized USASCII (per the DNS spec),
  2223. * is this characted special ("in need of quoting") ?
  2224. */
  2225. static int special(int ch)
  2226. {
  2227. switch (ch) {
  2228. case 0x22: /* '"' */
  2229. case 0x2E: /* '.' */
  2230. case 0x3B: /* ';' */
  2231. case 0x5C: /* '\\' */
  2232. /* Special modifiers in zone files. */
  2233. case 0x40: /* '@' */
  2234. case 0x24: /* '$' */
  2235. return 1;
  2236. default:
  2237. return 0;
  2238. }
  2239. }
  2240. /*
  2241. * ns_name_uncompress(msg, eom, src, dst, dstsiz)
  2242. * Expand compressed domain name to presentation format.
  2243. * return:
  2244. * Number of bytes read out of `src', or -1 (with errno set).
  2245. * note:
  2246. * Root domain returns as "." not "".
  2247. */
  2248. int ns_name_uncompress(const u_char *msg, const u_char *eom,
  2249. const u_char *src, char *dst, size_t dstsiz)
  2250. {
  2251. u_char tmp[NS_MAXCDNAME];
  2252. int n;
  2253. n = ns_name_unpack(msg, eom, src, tmp, sizeof tmp);
  2254. if (n == -1)
  2255. return -1;
  2256. if (ns_name_ntop(tmp, dst, dstsiz) == -1)
  2257. return -1;
  2258. return n;
  2259. }
  2260. libc_hidden_def(ns_name_uncompress)
  2261. /*
  2262. * ns_name_ntop(src, dst, dstsiz)
  2263. * Convert an encoded domain name to printable ascii as per RFC1035.
  2264. * return:
  2265. * Number of bytes written to buffer, or -1 (with errno set)
  2266. * notes:
  2267. * The root is returned as "."
  2268. * All other domains are returned in non absolute form
  2269. */
  2270. int ns_name_ntop(const u_char *src, char *dst, size_t dstsiz)
  2271. {
  2272. static const char digits[] = "0123456789";
  2273. const u_char *cp;
  2274. char *dn, *eom;
  2275. u_char c;
  2276. u_int n;
  2277. cp = src;
  2278. dn = dst;
  2279. eom = dst + dstsiz;
  2280. while ((n = *cp++) != 0) {
  2281. if ((n & NS_CMPRSFLGS) != 0) {
  2282. /* Some kind of compression pointer. */
  2283. __set_errno(EMSGSIZE);
  2284. return -1;
  2285. }
  2286. if (dn != dst) {
  2287. if (dn >= eom) {
  2288. __set_errno(EMSGSIZE);
  2289. return -1;
  2290. }
  2291. *dn++ = '.';
  2292. }
  2293. if (dn + n >= eom) {
  2294. __set_errno(EMSGSIZE);
  2295. return -1;
  2296. }
  2297. for (; n > 0; n--) {
  2298. c = *cp++;
  2299. if (special(c)) {
  2300. if (dn + 1 >= eom) {
  2301. __set_errno(EMSGSIZE);
  2302. return -1;
  2303. }
  2304. *dn++ = '\\';
  2305. *dn++ = (char)c;
  2306. } else if (!printable(c)) {
  2307. if (dn + 3 >= eom) {
  2308. __set_errno(EMSGSIZE);
  2309. return -1;
  2310. }
  2311. *dn++ = '\\';
  2312. *dn++ = digits[c / 100];
  2313. *dn++ = digits[(c % 100) / 10];
  2314. *dn++ = digits[c % 10];
  2315. } else {
  2316. if (dn >= eom) {
  2317. __set_errno(EMSGSIZE);
  2318. return -1;
  2319. }
  2320. *dn++ = (char)c;
  2321. }
  2322. }
  2323. }
  2324. if (dn == dst) {
  2325. if (dn >= eom) {
  2326. __set_errno(EMSGSIZE);
  2327. return -1;
  2328. }
  2329. *dn++ = '.';
  2330. }
  2331. if (dn >= eom) {
  2332. __set_errno(EMSGSIZE);
  2333. return -1;
  2334. }
  2335. *dn++ = '\0';
  2336. return (dn - dst);
  2337. }
  2338. libc_hidden_def(ns_name_ntop)
  2339. /*
  2340. * ns_name_unpack(msg, eom, src, dst, dstsiz)
  2341. * Unpack a domain name from a message, source may be compressed.
  2342. * return:
  2343. * -1 if it fails, or consumed octets if it succeeds.
  2344. */
  2345. int ns_name_unpack(const u_char *msg, const u_char *eom, const u_char *src,
  2346. u_char *dst, size_t dstsiz)
  2347. {
  2348. const u_char *srcp, *dstlim;
  2349. u_char *dstp;
  2350. int n, len, checked;
  2351. len = -1;
  2352. checked = 0;
  2353. dstp = dst;
  2354. srcp = src;
  2355. dstlim = dst + dstsiz;
  2356. if (srcp < msg || srcp >= eom) {
  2357. __set_errno(EMSGSIZE);
  2358. return -1;
  2359. }
  2360. /* Fetch next label in domain name. */
  2361. while ((n = *srcp++) != 0) {
  2362. /* Check for indirection. */
  2363. switch (n & NS_CMPRSFLGS) {
  2364. case 0:
  2365. /* Limit checks. */
  2366. if (dstp + n + 1 >= dstlim || srcp + n >= eom) {
  2367. __set_errno(EMSGSIZE);
  2368. return -1;
  2369. }
  2370. checked += n + 1;
  2371. *dstp++ = n;
  2372. memcpy(dstp, srcp, n);
  2373. dstp += n;
  2374. srcp += n;
  2375. break;
  2376. case NS_CMPRSFLGS:
  2377. if (srcp >= eom) {
  2378. __set_errno(EMSGSIZE);
  2379. return -1;
  2380. }
  2381. if (len < 0)
  2382. len = srcp - src + 1;
  2383. srcp = msg + (((n & 0x3f) << 8) | (*srcp & 0xff));
  2384. if (srcp < msg || srcp >= eom) { /* Out of range. */
  2385. __set_errno(EMSGSIZE);
  2386. return -1;
  2387. }
  2388. checked += 2;
  2389. /*
  2390. * Check for loops in the compressed name;
  2391. * if we've looked at the whole message,
  2392. * there must be a loop.
  2393. */
  2394. if (checked >= eom - msg) {
  2395. __set_errno(EMSGSIZE);
  2396. return -1;
  2397. }
  2398. break;
  2399. default:
  2400. __set_errno(EMSGSIZE);
  2401. return -1; /* flag error */
  2402. }
  2403. }
  2404. *dstp = '\0';
  2405. if (len < 0)
  2406. len = srcp - src;
  2407. return len;
  2408. }
  2409. libc_hidden_def(ns_name_unpack)
  2410. #endif /* L_ns_name */
  2411. #ifdef L_res_init
  2412. /* Protected by __resolv_lock */
  2413. struct __res_state _res;
  2414. /* Will be called under __resolv_lock. */
  2415. static void res_sync_func(void)
  2416. {
  2417. struct __res_state *rp = &(_res);
  2418. int n;
  2419. /* If we didn't get malloc failure earlier... */
  2420. if (__nameserver != (void*) &__local_nameserver) {
  2421. /* TODO:
  2422. * if (__nameservers < rp->nscount) - try to grow __nameserver[]?
  2423. */
  2424. #ifdef __UCLIBC_HAS_IPV6__
  2425. if (__nameservers > rp->_u._ext.nscount)
  2426. __nameservers = rp->_u._ext.nscount;
  2427. n = __nameservers;
  2428. while (--n >= 0)
  2429. __nameserver[n].sa6 = *rp->_u._ext.nsaddrs[n]; /* struct copy */
  2430. #else /* IPv4 only */
  2431. if (__nameservers > rp->nscount)
  2432. __nameservers = rp->nscount;
  2433. n = __nameservers;
  2434. while (--n >= 0)
  2435. __nameserver[n].sa4 = rp->nsaddr_list[n]; /* struct copy */
  2436. #endif
  2437. }
  2438. /* Extend and comment what program is known
  2439. * to use which _res.XXX member(s).
  2440. __resolv_opts = rp->options;
  2441. ...
  2442. */
  2443. }
  2444. /* Our res_init never fails (always returns 0) */
  2445. int res_init(void)
  2446. {
  2447. struct __res_state *rp = &(_res);
  2448. int i;
  2449. int n;
  2450. #ifdef __UCLIBC_HAS_IPV6__
  2451. int m = 0;
  2452. #endif
  2453. __UCLIBC_MUTEX_LOCK(__resolv_lock);
  2454. __close_nameservers();
  2455. __open_nameservers();
  2456. __res_sync = res_sync_func;
  2457. memset(rp, 0, sizeof(*rp));
  2458. rp->options = RES_INIT;
  2459. #ifdef __UCLIBC_HAS_COMPAT_RES_STATE__
  2460. rp->retrans = RES_TIMEOUT;
  2461. rp->retry = 4;
  2462. /*TODO: pulls in largish static buffers... use simpler one? */
  2463. rp->id = random();
  2464. #endif
  2465. rp->ndots = 1;
  2466. #ifdef __UCLIBC_HAS_EXTRA_COMPAT_RES_STATE__
  2467. rp->_vcsock = -1;
  2468. #endif
  2469. n = __searchdomains;
  2470. if (n > ARRAY_SIZE(rp->dnsrch))
  2471. n = ARRAY_SIZE(rp->dnsrch);
  2472. for (i = 0; i < n; i++)
  2473. rp->dnsrch[i] = __searchdomain[i];
  2474. /* copy nameservers' addresses */
  2475. i = 0;
  2476. #ifdef __UCLIBC_HAS_IPV4__
  2477. n = 0;
  2478. while (n < ARRAY_SIZE(rp->nsaddr_list) && i < __nameservers) {
  2479. if (__nameserver[i].sa.sa_family == AF_INET) {
  2480. rp->nsaddr_list[n] = __nameserver[i].sa4; /* struct copy */
  2481. #ifdef __UCLIBC_HAS_IPV6__
  2482. if (m < ARRAY_SIZE(rp->_u._ext.nsaddrs)) {
  2483. rp->_u._ext.nsaddrs[m] = (void*) &rp->nsaddr_list[n];
  2484. m++;
  2485. }
  2486. #endif
  2487. n++;
  2488. }
  2489. #ifdef __UCLIBC_HAS_IPV6__
  2490. if (__nameserver[i].sa.sa_family == AF_INET6
  2491. && m < ARRAY_SIZE(rp->_u._ext.nsaddrs)
  2492. ) {
  2493. struct sockaddr_in6 *sa6 = malloc(sizeof(sa6));
  2494. if (sa6) {
  2495. *sa6 = __nameserver[i].sa6; /* struct copy */
  2496. rp->_u._ext.nsaddrs[m] = sa6;
  2497. m++;
  2498. }
  2499. }
  2500. #endif
  2501. i++;
  2502. }
  2503. rp->nscount = n;
  2504. #ifdef __UCLIBC_HAS_IPV6__
  2505. rp->_u._ext.nscount = m;
  2506. #endif
  2507. #else /* IPv6 only */
  2508. while (m < ARRAY_SIZE(rp->_u._ext.nsaddrs) && i < __nameservers) {
  2509. struct sockaddr_in6 *sa6 = malloc(sizeof(sa6));
  2510. if (sa6) {
  2511. *sa6 = __nameserver[i].sa6; /* struct copy */
  2512. rp->_u._ext.nsaddrs[m] = sa6;
  2513. m++;
  2514. }
  2515. i++;
  2516. }
  2517. rp->_u._ext.nscount = m;
  2518. #endif
  2519. __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
  2520. return 0;
  2521. }
  2522. libc_hidden_def(res_init)
  2523. #ifdef __UCLIBC_HAS_BSD_RES_CLOSE__
  2524. void res_close(void)
  2525. {
  2526. __UCLIBC_MUTEX_LOCK(__resolv_lock);
  2527. __close_nameservers();
  2528. __res_sync = NULL;
  2529. #ifdef __UCLIBC_HAS_IPV6__
  2530. {
  2531. char *p1 = (char*) &(_res.nsaddr_list[0]);
  2532. int m = 0;
  2533. /* free nsaddrs[m] if they do not point to nsaddr_list[x] */
  2534. while (m < ARRAY_SIZE(_res._u._ext.nsaddrs)) {
  2535. char *p2 = (char*)(_res._u._ext.nsaddrs[m]);
  2536. if (p2 < p1 || (p2 - p1) > sizeof(_res.nsaddr_list))
  2537. free(p2);
  2538. }
  2539. }
  2540. #endif
  2541. memset(&_res, 0, sizeof(_res));
  2542. __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
  2543. }
  2544. #endif
  2545. #endif /* L_res_init */
  2546. #ifdef L_res_query
  2547. int res_query(const char *dname, int class, int type,
  2548. unsigned char *answer, int anslen)
  2549. {
  2550. int i;
  2551. unsigned char * packet = NULL;
  2552. struct resolv_answer a;
  2553. if (!dname || class != 1 /* CLASS_IN */) {
  2554. h_errno = NO_RECOVERY;
  2555. return -1;
  2556. }
  2557. memset(&a, '\0', sizeof(a));
  2558. i = __dns_lookup(dname, type, &packet, &a);
  2559. if (i < 0) {
  2560. h_errno = TRY_AGAIN;
  2561. return -1;
  2562. }
  2563. free(a.dotted);
  2564. if (a.atype == type) { /* CNAME */
  2565. if (i > anslen)
  2566. i = anslen;
  2567. memcpy(answer, packet, i);
  2568. }
  2569. free(packet);
  2570. return i;
  2571. }
  2572. libc_hidden_def(res_query)
  2573. /*
  2574. * Formulate a normal query, send, and retrieve answer in supplied buffer.
  2575. * Return the size of the response on success, -1 on error.
  2576. * If enabled, implement search rules until answer or unrecoverable failure
  2577. * is detected. Error code, if any, is left in h_errno.
  2578. */
  2579. #define __TRAILING_DOT (1<<0)
  2580. #define __GOT_NODATA (1<<1)
  2581. #define __GOT_SERVFAIL (1<<2)
  2582. #define __TRIED_AS_IS (1<<3)
  2583. int res_search(const char *name, int class, int type, u_char *answer,
  2584. int anslen)
  2585. {
  2586. const char *cp, * const *domain;
  2587. HEADER *hp = (HEADER *)(void *)answer;
  2588. unsigned dots;
  2589. unsigned state;
  2590. int ret, saved_herrno;
  2591. uint32_t _res_options;
  2592. unsigned _res_ndots;
  2593. char **_res_dnsrch;
  2594. if (!name || !answer) {
  2595. h_errno = NETDB_INTERNAL;
  2596. return -1;
  2597. }
  2598. again:
  2599. __UCLIBC_MUTEX_LOCK(__resolv_lock);
  2600. _res_options = _res.options;
  2601. _res_ndots = _res.ndots;
  2602. _res_dnsrch = _res.dnsrch;
  2603. __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
  2604. if (!(_res_options & RES_INIT)) {
  2605. res_init(); /* our res_init never fails */
  2606. goto again;
  2607. }
  2608. state = 0;
  2609. errno = 0;
  2610. h_errno = HOST_NOT_FOUND; /* default, if we never query */
  2611. dots = 0;
  2612. for (cp = name; *cp; cp++)
  2613. dots += (*cp == '.');
  2614. if (cp > name && *--cp == '.')
  2615. state |= __TRAILING_DOT;
  2616. /*
  2617. * If there are dots in the name already, let's just give it a try
  2618. * 'as is'. The threshold can be set with the "ndots" option.
  2619. */
  2620. saved_herrno = -1;
  2621. if (dots >= _res_ndots) {
  2622. ret = res_querydomain(name, NULL, class, type, answer, anslen);
  2623. if (ret > 0)
  2624. return ret;
  2625. saved_herrno = h_errno;
  2626. state |= __TRIED_AS_IS;
  2627. }
  2628. /*
  2629. * We do at least one level of search if
  2630. * - there is no dot and RES_DEFNAME is set, or
  2631. * - there is at least one dot, there is no trailing dot,
  2632. * and RES_DNSRCH is set.
  2633. */
  2634. if ((!dots && (_res_options & RES_DEFNAMES))
  2635. || (dots && !(state & __TRAILING_DOT) && (_res_options & RES_DNSRCH))
  2636. ) {
  2637. bool done = 0;
  2638. for (domain = (const char * const *)_res_dnsrch;
  2639. *domain && !done;
  2640. domain++) {
  2641. ret = res_querydomain(name, *domain, class, type,
  2642. answer, anslen);
  2643. if (ret > 0)
  2644. return ret;
  2645. /*
  2646. * If no server present, give up.
  2647. * If name isn't found in this domain,
  2648. * keep trying higher domains in the search list
  2649. * (if that's enabled).
  2650. * On a NO_DATA error, keep trying, otherwise
  2651. * a wildcard entry of another type could keep us
  2652. * from finding this entry higher in the domain.
  2653. * If we get some other error (negative answer or
  2654. * server failure), then stop searching up,
  2655. * but try the input name below in case it's
  2656. * fully-qualified.
  2657. */
  2658. if (errno == ECONNREFUSED) {
  2659. h_errno = TRY_AGAIN;
  2660. return -1;
  2661. }
  2662. switch (h_errno) {
  2663. case NO_DATA:
  2664. state |= __GOT_NODATA;
  2665. /* FALLTHROUGH */
  2666. case HOST_NOT_FOUND:
  2667. /* keep trying */
  2668. break;
  2669. case TRY_AGAIN:
  2670. if (hp->rcode == SERVFAIL) {
  2671. /* try next search element, if any */
  2672. state |= __GOT_SERVFAIL;
  2673. break;
  2674. }
  2675. /* FALLTHROUGH */
  2676. default:
  2677. /* anything else implies that we're done */
  2678. done = 1;
  2679. }
  2680. /*
  2681. * if we got here for some reason other than DNSRCH,
  2682. * we only wanted one iteration of the loop, so stop.
  2683. */
  2684. if (!(_res_options & RES_DNSRCH))
  2685. done = 1;
  2686. }
  2687. }
  2688. /*
  2689. * if we have not already tried the name "as is", do that now.
  2690. * note that we do this regardless of how many dots were in the
  2691. * name or whether it ends with a dot.
  2692. */
  2693. if (!(state & __TRIED_AS_IS)) {
  2694. ret = res_querydomain(name, NULL, class, type, answer, anslen);
  2695. if (ret > 0)
  2696. return ret;
  2697. }
  2698. /*
  2699. * if we got here, we didn't satisfy the search.
  2700. * if we did an initial full query, return that query's h_errno
  2701. * (note that we wouldn't be here if that query had succeeded).
  2702. * else if we ever got a nodata, send that back as the reason.
  2703. * else send back meaningless h_errno, that being the one from
  2704. * the last DNSRCH we did.
  2705. */
  2706. if (saved_herrno != -1)
  2707. h_errno = saved_herrno;
  2708. else if (state & __GOT_NODATA)
  2709. h_errno = NO_DATA;
  2710. else if (state & __GOT_SERVFAIL)
  2711. h_errno = TRY_AGAIN;
  2712. return -1;
  2713. }
  2714. #undef __TRAILING_DOT
  2715. #undef __GOT_NODATA
  2716. #undef __GOT_SERVFAIL
  2717. #undef __TRIED_AS_IS
  2718. /*
  2719. * Perform a call on res_query on the concatenation of name and domain,
  2720. * removing a trailing dot from name if domain is NULL.
  2721. */
  2722. int res_querydomain(const char *name, const char *domain, int class, int type,
  2723. u_char * answer, int anslen)
  2724. {
  2725. char nbuf[MAXDNAME];
  2726. const char *longname = nbuf;
  2727. size_t n, d;
  2728. #ifdef DEBUG
  2729. uint32_t _res_options;
  2730. #endif
  2731. if (!name || !answer) {
  2732. h_errno = NETDB_INTERNAL;
  2733. return -1;
  2734. }
  2735. #ifdef DEBUG
  2736. again:
  2737. __UCLIBC_MUTEX_LOCK(__resolv_lock);
  2738. _res_options = _res.options;
  2739. __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
  2740. if (!(_res_options & RES_INIT)) {
  2741. res_init(); /* our res_init never fails */
  2742. goto again:
  2743. }
  2744. if (_res_options & RES_DEBUG)
  2745. printf(";; res_querydomain(%s, %s, %d, %d)\n",
  2746. name, (domain ? domain : "<Nil>"), class, type);
  2747. #endif
  2748. if (domain == NULL) {
  2749. /*
  2750. * Check for trailing '.';
  2751. * copy without '.' if present.
  2752. */
  2753. n = strlen(name);
  2754. if (n + 1 > sizeof(nbuf)) {
  2755. h_errno = NO_RECOVERY;
  2756. return -1;
  2757. }
  2758. if (n > 0 && name[--n] == '.') {
  2759. strncpy(nbuf, name, n);
  2760. nbuf[n] = '\0';
  2761. } else
  2762. longname = name;
  2763. } else {
  2764. n = strlen(name);
  2765. d = strlen(domain);
  2766. if (n + 1 + d + 1 > sizeof(nbuf)) {
  2767. h_errno = NO_RECOVERY;
  2768. return -1;
  2769. }
  2770. snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
  2771. }
  2772. return res_query(longname, class, type, answer, anslen);
  2773. }
  2774. libc_hidden_def(res_querydomain)
  2775. /* res_mkquery */
  2776. /* res_send */
  2777. /* dn_comp */
  2778. /* dn_expand */
  2779. #endif
  2780. /* vi: set sw=4 ts=4: */