resolv.c 78 KB

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