eventdns.c 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176
  1. /* $Id$ */
  2. /* The original version of this module was written by Adam Langley; for
  3. * a history of modifications, check out the subversion logs.
  4. *
  5. * When editing this module, try to keep it re-mergeable by Adam. Don't
  6. * reformat the whitespace, add Tor dependencies, or so on.
  7. *
  8. * TODO:
  9. * - Replace all externally visible magic numbers with #defined constants.
  10. * - Write documentation for APIs of all external functions.
  11. */
  12. /* Async DNS Library
  13. * Adam Langley <agl@imperialviolet.org>
  14. * Public Domain code
  15. *
  16. * This software is Public Domain. To view a copy of the public domain dedication,
  17. * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
  18. * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
  19. *
  20. * I ask and expect, but do not require, that all derivative works contain an
  21. * attribution similar to:
  22. * Parts developed by Adam Langley <agl@imperialviolet.org>
  23. *
  24. * You may wish to replace the word "Parts" with something else depending on
  25. * the amount of original code.
  26. *
  27. * (Derivative works does not include programs which link against, run or include
  28. * the source verbatim in their source distributions)
  29. *
  30. * Version: 0.1b
  31. */
  32. #include "eventdns_tor.h"
  33. #include <sys/types.h>
  34. /* #define NDEBUG */
  35. #ifndef DNS_USE_CPU_CLOCK_FOR_ID
  36. #ifndef DNS_USE_GETTIMEOFDAY_FOR_ID
  37. #ifndef DNS_USE_OPENSSL_FOR_ID
  38. #error Must configure at least one id generation method.
  39. #error Please see the documentation.
  40. #endif
  41. #endif
  42. #endif
  43. /* #define _POSIX_C_SOURCE 200507 */
  44. #define _GNU_SOURCE
  45. #ifdef DNS_USE_CPU_CLOCK_FOR_ID
  46. #ifdef DNS_USE_OPENSSL_FOR_ID
  47. #error Multiple id options selected
  48. #endif
  49. #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
  50. #error Multiple id options selected
  51. #endif
  52. #include <time.h>
  53. #endif
  54. #ifdef DNS_USE_OPENSSL_FOR_ID
  55. #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
  56. #error Multiple id options selected
  57. #endif
  58. #include <openssl/rand.h>
  59. #endif
  60. #define _FORTIFY_SOURCE 3
  61. #include <string.h>
  62. #ifdef HAVE_FCNTL_H
  63. #include <fcntl.h>
  64. #endif
  65. #ifdef HAVE_SYS_TIME_H
  66. #include <sys/time.h>
  67. #endif
  68. #ifdef HAVE_STDINT_H
  69. #include <stdint.h>
  70. #endif
  71. #include <stdlib.h>
  72. #include <string.h>
  73. #include <errno.h>
  74. #include <assert.h>
  75. #ifdef HAVE_UNISTD_H
  76. #include <unistd.h>
  77. #endif
  78. #ifdef HAVE_LIMITS_H
  79. #include <limits.h>
  80. #endif
  81. #include <sys/stat.h>
  82. #include <ctype.h>
  83. #include <stdio.h>
  84. #include <stdarg.h>
  85. #include "eventdns.h"
  86. #ifdef WIN32
  87. #include <windows.h>
  88. #include <winsock2.h>
  89. #include <iphlpapi.h>
  90. #else
  91. #include <sys/socket.h>
  92. #include <netinet/in.h>
  93. #include <arpa/inet.h>
  94. #endif
  95. #ifdef HAVE_NETINET_IN6_H
  96. #include <netinet6/in6.h>
  97. #endif
  98. #ifdef WIN32
  99. typedef int socklen_t;
  100. #endif
  101. #define EVDNS_LOG_DEBUG 0
  102. #define EVDNS_LOG_WARN 1
  103. #ifndef HOST_NAME_MAX
  104. #define HOST_NAME_MAX 255
  105. #endif
  106. #ifndef NDEBUG
  107. #include <stdio.h>
  108. #endif
  109. /*XXXX020 for debugging possible memory leaks. */
  110. #define malloc(x) tor_malloc(x)
  111. #define realloc(x,y) tor_realloc((x),(y))
  112. #define free(x) tor_free(x)
  113. #define _free(x) _tor_free(x)
  114. #undef MIN
  115. #define MIN(a,b) ((a)<(b)?(a):(b))
  116. #if 0
  117. #ifdef __USE_ISOC99B
  118. /* libevent doesn't work without this */
  119. typedef uint8_t u_char;
  120. typedef unsigned int uint;
  121. #endif
  122. #endif
  123. #include <event.h>
  124. #define u64 uint64_t
  125. #define u32 uint32_t
  126. #define u16 uint16_t
  127. #define u8 uint8_t
  128. #define MAX_ADDRS 4 /* maximum number of addresses from a single packet */
  129. /* which we bother recording */
  130. #define TYPE_A EVDNS_TYPE_A
  131. #define TYPE_PTR EVDNS_TYPE_PTR
  132. #define TYPE_AAAA EVDNS_TYPE_AAAA
  133. #define CLASS_INET EVDNS_CLASS_INET
  134. #define CLEAR(x) do { memset((x), 0, sizeof(*(x))); } while(0)
  135. struct request {
  136. u8 *request; /* the dns packet data */
  137. unsigned int request_len;
  138. int reissue_count;
  139. int tx_count; /* the number of times that this packet has been sent */
  140. unsigned int request_type; /* TYPE_PTR or TYPE_A */
  141. void *user_pointer; /* the pointer given to us for this request */
  142. evdns_callback_type user_callback;
  143. struct nameserver *ns; /* the server which we last sent it */
  144. /* elements used by the searching code */
  145. int search_index;
  146. struct search_state *search_state;
  147. char *search_origname; /* needs to be free()ed */
  148. int search_flags;
  149. /* these objects are kept in a circular list */
  150. struct request *next, *prev;
  151. struct event timeout_event;
  152. u16 trans_id; /* the transaction id */
  153. char request_appended; /* true if the request pointer is data which follows this struct */
  154. char transmit_me; /* needs to be transmitted */
  155. };
  156. #ifndef HAVE_STRUCT_IN6_ADDR
  157. struct in6_addr {
  158. u8 s6_addr[16];
  159. };
  160. #endif
  161. struct reply {
  162. unsigned int type;
  163. unsigned int have_answer;
  164. union {
  165. struct {
  166. u32 addrcount;
  167. u32 addresses[MAX_ADDRS];
  168. } a;
  169. struct {
  170. u32 addrcount;
  171. struct in6_addr addresses[MAX_ADDRS];
  172. } aaaa;
  173. struct {
  174. char name[HOST_NAME_MAX];
  175. } ptr;
  176. } data;
  177. };
  178. struct nameserver {
  179. int socket; /* a connected UDP socket */
  180. u32 address;
  181. int failed_times; /* number of times which we have given this server a chance */
  182. int timedout; /* number of times in a row a request has timed out */
  183. struct event event;
  184. /* these objects are kept in a circular list */
  185. struct nameserver *next, *prev;
  186. struct event timeout_event; /* used to keep the timeout for */
  187. /* when we next probe this server. */
  188. /* Valid if state == 0 */
  189. char state; /* zero if we think that this server is down */
  190. char choked; /* true if we have an EAGAIN from this server's socket */
  191. char write_waiting; /* true if we are waiting for EV_WRITE events */
  192. };
  193. static struct request *req_head = NULL, *req_waiting_head = NULL;
  194. static struct nameserver *server_head = NULL;
  195. /* Represents a local port where we're listening for DNS requests. Right now, */
  196. /* only UDP is supported. */
  197. struct evdns_server_port {
  198. int socket; /* socket we use to read queries and write replies. */
  199. int refcnt; /* reference count. */
  200. char choked; /* Are we currently blocked from writing? */
  201. char closing; /* Are we trying to close this port, pending writes? */
  202. evdns_request_callback_fn_type user_callback; /* Fn to handle requests */
  203. void *user_data; /* Opaque pointer passed to user_callback */
  204. struct event event; /* Read/write event */
  205. /* circular list of replies that we want to write. */
  206. struct server_request *pending_replies;
  207. };
  208. /* Represents part of a reply being built. (That is, a single RR.) */
  209. struct server_reply_item {
  210. struct server_reply_item *next; /* next item in sequence. */
  211. char *name; /* name part of the RR */
  212. u16 type : 16; /* The RR type */
  213. u16 class : 16; /* The RR class (usually CLASS_INET) */
  214. u32 ttl; /* The RR TTL */
  215. char is_name; /* True iff data is a label */
  216. u16 datalen; /* Length of data; -1 if data is a label */
  217. void *data; /* The contents of the RR */
  218. };
  219. /* Represents a request that we've received as a DNS server, and holds */
  220. /* the components of the reply as we're constructing it. */
  221. struct server_request {
  222. /* Pointers to the next and previous entries on the list of replies */
  223. /* that we're waiting to write. Only set if we have tried to respond */
  224. /* and gotten EAGAIN. */
  225. struct server_request *next_pending;
  226. struct server_request *prev_pending;
  227. u16 trans_id; /* Transaction id. */
  228. struct evdns_server_port *port; /* Which port received this request on? */
  229. struct sockaddr_storage addr; /* Where to send the response */
  230. socklen_t addrlen; /* length of addr */
  231. int n_answer; /* how many answer RRs have been set? */
  232. int n_authority; /* how many authority RRs have been set? */
  233. int n_additional; /* how many additional RRs have been set? */
  234. struct server_reply_item *answer; /* linked list of answer RRs */
  235. struct server_reply_item *authority; /* linked list of authority RRs */
  236. struct server_reply_item *additional; /* linked list of additional RRs */
  237. /* Constructed response. Only set once we're ready to send a reply. */
  238. /* Once this is set, the RR fields are cleared, and no more should be set. */
  239. char *response;
  240. size_t response_len;
  241. /* Caller-visible fields: flags, questions. */
  242. struct evdns_server_request base;
  243. };
  244. /* helper macro */
  245. #define OFFSET_OF(st, member) ((off_t) (((char*)&((st*)0)->member)-(char*)0))
  246. /* Given a pointer to an evdns_server_request, get the corresponding */
  247. /* server_request. */
  248. #define TO_SERVER_REQUEST(base_ptr) \
  249. ((struct server_request*) \
  250. (((char*)(base_ptr) - OFFSET_OF(struct server_request, base))))
  251. /* The number of good nameservers that we have */
  252. static int global_good_nameservers = 0;
  253. /* inflight requests are contained in the req_head list */
  254. /* and are actually going out across the network */
  255. static int global_requests_inflight = 0;
  256. /* requests which aren't inflight are in the waiting list */
  257. /* and are counted here */
  258. static int global_requests_waiting = 0;
  259. static int global_max_requests_inflight = 64;
  260. static struct timeval global_timeout = {5, 0}; /* 5 seconds */
  261. static int global_max_reissues = 1; /* a reissue occurs when we get some errors from the server */
  262. static int global_max_retransmits = 3; /* number of times we'll retransmit a request which timed out */
  263. /* number of timeouts in a row before we consider this server to be down */
  264. static int global_max_nameserver_timeout = 3;
  265. /* These are the timeout values for nameservers. If we find a nameserver is down */
  266. /* we try to probe it at intervals as given below. Values are in seconds. */
  267. static const struct timeval global_nameserver_timeouts[] = {{10, 0}, {60, 0}, {300, 0}, {900, 0}, {3600, 0}};
  268. static const int global_nameserver_timeouts_length = sizeof(global_nameserver_timeouts)/sizeof(struct timeval);
  269. static struct nameserver *nameserver_pick(void);
  270. static void evdns_request_insert(struct request *req, struct request **head);
  271. static void nameserver_ready_callback(int fd, short events, void *arg);
  272. static int evdns_transmit(void);
  273. static int evdns_request_transmit(struct request *req);
  274. static void nameserver_send_probe(struct nameserver *const ns);
  275. static void search_request_finished(struct request *const);
  276. static int search_try_next(struct request *const req);
  277. static int search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg);
  278. static void evdns_requests_pump_waiting_queue(void);
  279. static u16 transaction_id_pick(void);
  280. static struct request *request_new(int type, const char *name, int flags, evdns_callback_type callback, void *ptr);
  281. static void request_submit(struct request *req);
  282. static int server_request_free(struct server_request *req);
  283. static void server_request_free_answers(struct server_request *req);
  284. static void server_port_free(struct evdns_server_port *port);
  285. static void server_port_ready_callback(int fd, short events, void *arg);
  286. static int strtoint(const char *const str);
  287. #ifdef WIN32
  288. static int
  289. last_error(int sock)
  290. {
  291. int optval, optvallen=sizeof(optval);
  292. int err = WSAGetLastError();
  293. if (err == WSAEWOULDBLOCK && sock >= 0) {
  294. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
  295. &optvallen))
  296. return err;
  297. if (optval)
  298. return optval;
  299. }
  300. return err;
  301. }
  302. static int
  303. error_is_eagain(int err)
  304. {
  305. return err == EAGAIN || err == WSAEWOULDBLOCK;
  306. }
  307. static int
  308. inet_aton(const char *c, struct in_addr *addr)
  309. {
  310. uint32_t r;
  311. if (strcmp(c, "255.255.255.255") == 0) {
  312. addr->s_addr = 0xffffffffu;
  313. } else {
  314. r = inet_addr(c);
  315. if (r == INADDR_NONE)
  316. return 0;
  317. addr->s_addr = r;
  318. }
  319. return 1;
  320. }
  321. #define CLOSE_SOCKET(x) closesocket(x)
  322. #else
  323. #define last_error(sock) (errno)
  324. #define error_is_eagain(err) ((err) == EAGAIN)
  325. #define CLOSE_SOCKET(x) close(x)
  326. #endif
  327. #define ISSPACE(c) isspace((int)(unsigned char)(c))
  328. #define ISDIGIT(c) isdigit((int)(unsigned char)(c))
  329. #ifndef NDEBUG
  330. static const char *
  331. debug_ntoa(u32 address)
  332. {
  333. static char buf[32];
  334. u32 a = ntohl(address);
  335. snprintf(buf, sizeof(buf), "%d.%d.%d.%d",
  336. (int)(u8)((a>>24)&0xff),
  337. (int)(u8)((a>>16)&0xff),
  338. (int)(u8)((a>>8 )&0xff),
  339. (int)(u8)((a )&0xff));
  340. return buf;
  341. }
  342. #endif
  343. static evdns_debug_log_fn_type evdns_log_fn = NULL;
  344. void
  345. evdns_set_log_fn(evdns_debug_log_fn_type fn)
  346. {
  347. evdns_log_fn = fn;
  348. }
  349. #ifdef __GNUC__
  350. #define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3)))
  351. #else
  352. #define EVDNS_LOG_CHECK
  353. #endif
  354. static void _evdns_log(int warn, const char *fmt, ...) EVDNS_LOG_CHECK;
  355. static void
  356. _evdns_log(int warn, const char *fmt, ...)
  357. {
  358. va_list args;
  359. static char buf[512];
  360. if (!evdns_log_fn)
  361. return;
  362. va_start(args,fmt);
  363. #ifdef WIN32
  364. _vsnprintf(buf, sizeof(buf), fmt, args);
  365. #else
  366. vsnprintf(buf, sizeof(buf), fmt, args);
  367. #endif
  368. buf[sizeof(buf)-1] = '\0';
  369. evdns_log_fn(warn, buf);
  370. va_end(args);
  371. }
  372. #define log _evdns_log
  373. /* This walks the list of inflight requests to find the */
  374. /* one with a matching transaction id. Returns NULL on */
  375. /* failure */
  376. static struct request *
  377. request_find_from_trans_id(u16 trans_id) {
  378. struct request *req = req_head, *const started_at = req_head;
  379. if (req) {
  380. do {
  381. if (req->trans_id == trans_id) return req;
  382. req = req->next;
  383. } while (req != started_at);
  384. }
  385. return NULL;
  386. }
  387. /* a libevent callback function which is called when a nameserver */
  388. /* has gone down and we want to test if it has came back to life yet */
  389. static void
  390. nameserver_prod_callback(int fd, short events, void *arg) {
  391. struct nameserver *const ns = (struct nameserver *) arg;
  392. (void)fd;
  393. (void)events;
  394. nameserver_send_probe(ns);
  395. }
  396. /* a libevent callback which is called when a nameserver probe (to see if */
  397. /* it has come back to life) times out. We increment the count of failed_times */
  398. /* and wait longer to send the next probe packet. */
  399. static void
  400. nameserver_probe_failed(struct nameserver *const ns) {
  401. const struct timeval * timeout;
  402. (void) evtimer_del(&ns->timeout_event);
  403. CLEAR(&ns->timeout_event);
  404. if (ns->state == 1) {
  405. /* This can happen if the nameserver acts in a way which makes us mark */
  406. /* it as bad and then starts sending good replies. */
  407. return;
  408. }
  409. timeout =
  410. &global_nameserver_timeouts[MIN(ns->failed_times,
  411. global_nameserver_timeouts_length - 1)];
  412. ns->failed_times++;
  413. evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
  414. if (evtimer_add(&ns->timeout_event, (struct timeval *) timeout) < 0) {
  415. log(EVDNS_LOG_WARN,
  416. "Error from libevent when adding timer event for %s",
  417. debug_ntoa(ns->address));
  418. /* ???? Do more? */
  419. }
  420. }
  421. /* called when a nameserver has been deemed to have failed. For example, too */
  422. /* many packets have timed out etc */
  423. static void
  424. nameserver_failed(struct nameserver *const ns, const char *msg) {
  425. struct request *req, *started_at;
  426. /* if this nameserver has already been marked as failed */
  427. /* then don't do anything */
  428. if (!ns->state) return;
  429. log(EVDNS_LOG_WARN, "Nameserver %s has failed: %s",
  430. debug_ntoa(ns->address), msg);
  431. global_good_nameservers--;
  432. assert(global_good_nameservers >= 0);
  433. if (global_good_nameservers == 0) {
  434. log(EVDNS_LOG_WARN, "All nameservers have failed");
  435. }
  436. ns->state = 0;
  437. ns->failed_times = 1;
  438. evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
  439. if (evtimer_add(&ns->timeout_event, (struct timeval *) &global_nameserver_timeouts[0]) < 0) {
  440. log(EVDNS_LOG_WARN,
  441. "Error from libevent when adding timer event for %s",
  442. debug_ntoa(ns->address));
  443. /* ???? Do more? */
  444. }
  445. /* walk the list of inflight requests to see if any can be reassigned to */
  446. /* a different server. Requests in the waiting queue don't have a */
  447. /* nameserver assigned yet */
  448. /* if we don't have *any* good nameservers then there's no point */
  449. /* trying to reassign requests to one */
  450. if (!global_good_nameservers) return;
  451. req = req_head;
  452. started_at = req_head;
  453. if (req) {
  454. do {
  455. if (req->tx_count == 0 && req->ns == ns) {
  456. /* still waiting to go out, can be moved */
  457. /* to another server */
  458. req->ns = nameserver_pick();
  459. }
  460. req = req->next;
  461. } while (req != started_at);
  462. }
  463. }
  464. static void
  465. nameserver_up(struct nameserver *const ns) {
  466. if (ns->state) return;
  467. log(EVDNS_LOG_WARN, "Nameserver %s is back up",
  468. debug_ntoa(ns->address));
  469. evtimer_del(&ns->timeout_event);
  470. CLEAR(&ns->timeout_event);
  471. ns->state = 1;
  472. ns->failed_times = 0;
  473. ns->timedout = 0;
  474. global_good_nameservers++;
  475. }
  476. static void
  477. request_trans_id_set(struct request *const req, const u16 trans_id) {
  478. req->trans_id = trans_id;
  479. *((u16 *) req->request) = htons(trans_id);
  480. }
  481. /* Called to remove a request from a list and dealloc it. */
  482. /* head is a pointer to the head of the list it should be */
  483. /* removed from or NULL if the request isn't in a list. */
  484. static void
  485. request_finished(struct request *const req, struct request **head) {
  486. if (head) {
  487. if (req->next == req) {
  488. /* only item in the list */
  489. *head = NULL;
  490. } else {
  491. req->next->prev = req->prev;
  492. req->prev->next = req->next;
  493. if (*head == req) *head = req->next;
  494. }
  495. }
  496. log(EVDNS_LOG_DEBUG, "Removing timeout for request %lx",
  497. (unsigned long) req);
  498. evtimer_del(&req->timeout_event);
  499. CLEAR(&req->timeout_event);
  500. search_request_finished(req);
  501. global_requests_inflight--;
  502. if (!req->request_appended) {
  503. /* need to free the request data on it's own */
  504. free(req->request);
  505. } else {
  506. /* the request data is appended onto the header */
  507. /* so everything gets free()ed when we: */
  508. }
  509. CLEAR(req);
  510. _free(req);
  511. evdns_requests_pump_waiting_queue();
  512. }
  513. /* This is called when a server returns a funny error code. */
  514. /* We try the request again with another server. */
  515. /* */
  516. /* return: */
  517. /* 0 ok */
  518. /* 1 failed/reissue is pointless */
  519. static int
  520. request_reissue(struct request *req) {
  521. const struct nameserver *const last_ns = req->ns;
  522. /* the last nameserver should have been marked as failing */
  523. /* by the caller of this function, therefore pick will try */
  524. /* not to return it */
  525. req->ns = nameserver_pick();
  526. if (req->ns == last_ns) {
  527. /* ... but pick did return it */
  528. /* not a lot of point in trying again with the */
  529. /* same server */
  530. return 1;
  531. }
  532. req->reissue_count++;
  533. req->tx_count = 0;
  534. req->transmit_me = 1;
  535. return 0;
  536. }
  537. /* this function looks for space on the inflight queue and promotes */
  538. /* requests from the waiting queue if it can. */
  539. static void
  540. evdns_requests_pump_waiting_queue(void) {
  541. while (global_requests_inflight < global_max_requests_inflight &&
  542. global_requests_waiting) {
  543. struct request *req;
  544. /* move a request from the waiting queue to the inflight queue */
  545. assert(req_waiting_head);
  546. if (req_waiting_head->next == req_waiting_head) {
  547. /* only one item in the queue */
  548. req = req_waiting_head;
  549. req_waiting_head = NULL;
  550. } else {
  551. req = req_waiting_head;
  552. req->next->prev = req->prev;
  553. req->prev->next = req->next;
  554. req_waiting_head = req->next;
  555. }
  556. global_requests_waiting--;
  557. global_requests_inflight++;
  558. req->ns = nameserver_pick();
  559. request_trans_id_set(req, transaction_id_pick());
  560. evdns_request_insert(req, &req_head);
  561. evdns_request_transmit(req);
  562. evdns_transmit();
  563. }
  564. }
  565. static void
  566. reply_callback(struct request *const req, u32 ttl, u32 err, struct reply *reply) {
  567. switch (req->request_type) {
  568. case TYPE_A:
  569. if (reply)
  570. req->user_callback(DNS_ERR_NONE, DNS_IPv4_A,
  571. reply->data.a.addrcount, ttl,
  572. reply->data.a.addresses,
  573. req->user_pointer);
  574. else
  575. req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
  576. return;
  577. case TYPE_PTR:
  578. if (reply) {
  579. char *name = reply->data.ptr.name;
  580. req->user_callback(DNS_ERR_NONE, DNS_PTR, 1, ttl,
  581. &name, req->user_pointer);
  582. } else {
  583. req->user_callback(err, 0, 0, 0, NULL,
  584. req->user_pointer);
  585. }
  586. return;
  587. case TYPE_AAAA:
  588. if (reply)
  589. req->user_callback(DNS_ERR_NONE, DNS_IPv6_AAAA,
  590. reply->data.aaaa.addrcount, ttl,
  591. reply->data.aaaa.addresses,
  592. req->user_pointer);
  593. else
  594. req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
  595. return;
  596. }
  597. assert(0);
  598. }
  599. /* this processes a parsed reply packet */
  600. static void
  601. reply_handle(struct request *const req, u16 flags, u32 ttl, struct reply *reply) {
  602. int error;
  603. static const int error_codes[] = {DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST, DNS_ERR_NOTIMPL, DNS_ERR_REFUSED};
  604. if (flags & 0x020f || !reply || !reply->have_answer) {
  605. /* there was an error */
  606. if (flags & 0x0200) {
  607. error = DNS_ERR_TRUNCATED;
  608. } else {
  609. u16 error_code = (flags & 0x000f) - 1;
  610. if (error_code > 4) {
  611. error = DNS_ERR_UNKNOWN;
  612. } else {
  613. error = error_codes[error_code];
  614. }
  615. }
  616. switch(error) {
  617. case DNS_ERR_NOTIMPL:
  618. case DNS_ERR_REFUSED:
  619. /* we regard these errors as marking a bad nameserver */
  620. if (req->reissue_count < global_max_reissues) {
  621. char msg[64];
  622. snprintf(msg, sizeof(msg), "Bad response %d (%s)",
  623. error, evdns_err_to_string(error));
  624. nameserver_failed(req->ns, msg);
  625. if (!request_reissue(req)) return;
  626. }
  627. break;
  628. case DNS_ERR_SERVERFAILED:
  629. /* rcode 2 (servfailed) sometimes means "we are broken" and
  630. * sometimes (with some binds) means "that request was very
  631. * confusing." Treat this as a timeout, not a failure.
  632. */
  633. /*XXXX refactor the parts of */
  634. log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver %s; "
  635. "will allow the request to time out.",
  636. debug_ntoa(req->ns->address));
  637. break;
  638. default:
  639. /* we got a good reply from the nameserver */
  640. nameserver_up(req->ns);
  641. }
  642. if (req->search_state && req->request_type != TYPE_PTR) {
  643. /* if we have a list of domains to search in, try the next one */
  644. if (!search_try_next(req)) {
  645. /* a new request was issued so this request is finished and */
  646. /* the user callback will be made when that request (or a */
  647. /* child of it) finishes. */
  648. request_finished(req, &req_head);
  649. return;
  650. }
  651. }
  652. /* all else failed. Pass the failure up */
  653. reply_callback(req, 0, error, NULL);
  654. request_finished(req, &req_head);
  655. } else {
  656. /* all ok, tell the user */
  657. reply_callback(req, ttl, 0, reply);
  658. nameserver_up(req->ns);
  659. request_finished(req, &req_head);
  660. }
  661. }
  662. static int
  663. name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
  664. int name_end = -1;
  665. int j = *idx;
  666. int ptr_count = 0;
  667. #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while(0)
  668. #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while(0)
  669. #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while(0)
  670. char *cp = name_out;
  671. const char *const end = name_out + name_out_len;
  672. /* Normally, names are a series of length prefixed strings terminated */
  673. /* with a length of 0 (the lengths are u8's < 63). */
  674. /* However, the length can start with a pair of 1 bits and that */
  675. /* means that the next 14 bits are a pointer within the current */
  676. /* packet. */
  677. for(;;) {
  678. u8 label_len;
  679. //if (j >= length) return -1;
  680. GET8(label_len);
  681. if (!label_len) break;
  682. if (label_len & 0xc0) {
  683. u8 ptr_low;
  684. GET8(ptr_low);
  685. if (name_end < 0) name_end = j;
  686. j = (((int)label_len & 0x3f) << 8) + ptr_low;
  687. /* Make sure that the target offset is in-bounds. */
  688. if (j < 0 || j >= length) return -1;
  689. /* If we've jumped more times than there are characters in the
  690. * message, we must have a loop. */
  691. if (++ptr_count > length) return -1;
  692. continue;
  693. }
  694. if (label_len > 63) return -1;
  695. if (cp != name_out) {
  696. if (cp + 1 >= end) return -1;
  697. *cp++ = '.';
  698. }
  699. if (cp + label_len >= end) return -1;
  700. memcpy(cp, packet + j, label_len);
  701. cp += label_len;
  702. j += label_len;
  703. }
  704. if (cp >= end) return -1;
  705. *cp = '\0';
  706. if (name_end < 0)
  707. *idx = j;
  708. else
  709. *idx = name_end;
  710. return 0;
  711. err:
  712. return -1;
  713. }
  714. /* parses a raw reply from a nameserver. */
  715. static int
  716. reply_parse(u8 *packet, int length) {
  717. int j = 0; /* index into packet */
  718. u16 _t; /* used by the macros */
  719. u32 _t32; /* used by the macros */
  720. char tmp_name[256]; /* used by the macros */
  721. u16 trans_id, questions, answers, authority, additional, datalength;
  722. u16 flags = 0;
  723. u32 ttl, ttl_r = 0xffffffff;
  724. struct reply reply;
  725. struct request *req = NULL;
  726. unsigned int i;
  727. GET16(trans_id);
  728. GET16(flags);
  729. GET16(questions);
  730. GET16(answers);
  731. GET16(authority);
  732. GET16(additional);
  733. (void) authority; /* suppress "unused variable" warnings. */
  734. (void) additional; /* suppress "unused variable" warnings. */
  735. req = request_find_from_trans_id(trans_id);
  736. /* if no request, can't do anything. */
  737. if (!req) return -1;
  738. memset(&reply, 0, sizeof(reply));
  739. /* If it's not an answer, it doesn't go with any of our requests. */
  740. if (!(flags & 0x8000)) return -1; /* must be an answer */
  741. if (flags & 0x020f) {
  742. /* there was an error */
  743. goto err;
  744. }
  745. /* if (!answers) return; */ /* must have an answer of some form */
  746. /* This macro skips a name in the DNS reply. */
  747. #define SKIP_NAME \
  748. do { tmp_name[0] = '\0'; \
  749. if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0) \
  750. goto err; \
  751. } while(0);
  752. reply.type = req->request_type;
  753. /* skip over each question in the reply */
  754. for (i = 0; i < questions; ++i) {
  755. /* the question looks like
  756. * <label:name><u16:type><u16:class>
  757. */
  758. SKIP_NAME;
  759. j += 4;
  760. if (j >= length) goto err;
  761. }
  762. /* now we have the answer section which looks like
  763. * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
  764. */
  765. for (i = 0; i < answers; ++i) {
  766. u16 type, class;
  767. /* XXX I'd be more comfortable if we actually checked the name */
  768. /* here. -NM */
  769. SKIP_NAME;
  770. GET16(type);
  771. GET16(class);
  772. GET32(ttl);
  773. GET16(datalength);
  774. if (type == TYPE_A && class == CLASS_INET) {
  775. int addrcount, addrtocopy;
  776. if (req->request_type != TYPE_A) {
  777. j += datalength; continue;
  778. }
  779. if ((datalength & 3) != 0) /* not an even number of As. */
  780. goto err;
  781. addrcount = datalength >> 2;
  782. addrtocopy = MIN(MAX_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
  783. ttl_r = MIN(ttl_r, ttl);
  784. /* we only bother with the first four addresses. */
  785. if (j + 4*addrtocopy > length) goto err;
  786. memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
  787. packet + j, 4*addrtocopy);
  788. j += 4*addrtocopy;
  789. reply.data.a.addrcount += addrtocopy;
  790. reply.have_answer = 1;
  791. if (reply.data.a.addrcount == MAX_ADDRS) break;
  792. } else if (type == TYPE_PTR && class == CLASS_INET) {
  793. if (req->request_type != TYPE_PTR) {
  794. j += datalength; continue;
  795. }
  796. if (name_parse(packet, length, &j, reply.data.ptr.name,
  797. sizeof(reply.data.ptr.name))<0)
  798. goto err;
  799. ttl_r = MIN(ttl_r, ttl);
  800. reply.have_answer = 1;
  801. break;
  802. } else if (type == TYPE_AAAA && class == CLASS_INET) {
  803. int addrcount, addrtocopy;
  804. if (req->request_type != TYPE_AAAA) {
  805. j += datalength; continue;
  806. }
  807. if ((datalength & 15) != 0) /* not an even number of AAAAs. */
  808. goto err;
  809. addrcount = datalength >> 4; /* each address is 16 bytes long */
  810. addrtocopy = MIN(MAX_ADDRS - reply.data.aaaa.addrcount, (unsigned)addrcount);
  811. ttl_r = MIN(ttl_r, ttl);
  812. /* we only bother with the first four addresses. */
  813. if (j + 16*addrtocopy > length) goto err;
  814. memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount],
  815. packet + j, 16*addrtocopy);
  816. reply.data.aaaa.addrcount += addrtocopy;
  817. j += 16*addrtocopy;
  818. reply.have_answer = 1;
  819. if (reply.data.aaaa.addrcount == MAX_ADDRS) break;
  820. } else {
  821. /* skip over any other type of resource */
  822. j += datalength;
  823. }
  824. }
  825. reply_handle(req, flags, ttl_r, &reply);
  826. return 0;
  827. err:
  828. if (req)
  829. reply_handle(req, flags, 0, NULL);
  830. return -1;
  831. }
  832. /* Parse a raw request (packet,length) sent to a nameserver port (port) from */
  833. /* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
  834. /* callback. */
  835. static int
  836. request_parse(u8 *packet, int length, struct evdns_server_port *port, struct sockaddr *addr, socklen_t addrlen)
  837. {
  838. int j = 0; /* index into packet */
  839. u16 _t; /* used by the macros */
  840. char tmp_name[256]; /* used by the macros */
  841. int i;
  842. u16 trans_id, flags, questions, answers, authority, additional;
  843. struct server_request *server_req = NULL;
  844. /* Get the header fields */
  845. GET16(trans_id);
  846. GET16(flags);
  847. GET16(questions);
  848. GET16(answers);
  849. GET16(authority);
  850. GET16(additional);
  851. if (flags & 0x8000) return -1; /* Must not be an answer. */
  852. flags &= 0x0110; /* Only RD and CD get preserved. */
  853. server_req = malloc(sizeof(struct server_request));
  854. if (server_req == NULL) return -1;
  855. memset(server_req, 0, sizeof(struct server_request));
  856. server_req->trans_id = trans_id;
  857. memcpy(&server_req->addr, addr, addrlen);
  858. server_req->addrlen = addrlen;
  859. server_req->base.flags = flags;
  860. server_req->base.nquestions = 0;
  861. server_req->base.questions = malloc(sizeof(struct evdns_server_question *) * questions);
  862. if (server_req->base.questions == NULL)
  863. goto err;
  864. for (i = 0; i < questions; ++i) {
  865. u16 type, class;
  866. struct evdns_server_question *q;
  867. int namelen;
  868. if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)
  869. goto err;
  870. GET16(type);
  871. GET16(class);
  872. namelen = strlen(tmp_name);
  873. q = malloc(sizeof(struct evdns_server_question) + namelen);
  874. if (!q)
  875. goto err;
  876. q->type = type;
  877. q->class = class;
  878. memcpy(q->name, tmp_name, namelen+1);
  879. server_req->base.questions[server_req->base.nquestions++] = q;
  880. }
  881. /* Ignore answers, authority, and additional. */
  882. server_req->port = port;
  883. port->refcnt++;
  884. /* Only standard queries are supported. */
  885. if (flags & 0x7800) {
  886. evdns_server_request_respond(&(server_req->base), DNS_ERR_NOTIMPL);
  887. return -1;
  888. }
  889. port->user_callback(&(server_req->base), port->user_data);
  890. return 0;
  891. err:
  892. if (server_req) {
  893. if (server_req->base.questions) {
  894. for (i = 0; i < server_req->base.nquestions; ++i)
  895. free(server_req->base.questions[i]);
  896. free(server_req->base.questions);
  897. }
  898. CLEAR(server_req);
  899. free(server_req);
  900. }
  901. return -1;
  902. #undef SKIP_NAME
  903. #undef GET32
  904. #undef GET16
  905. #undef GET8
  906. }
  907. /* Try to choose a strong transaction id which isn't already in flight */
  908. static u16
  909. transaction_id_pick(void) {
  910. for (;;) {
  911. const struct request *req = req_head, *started_at;
  912. #ifdef DNS_USE_CPU_CLOCK_FOR_ID
  913. struct timespec ts;
  914. u16 trans_id;
  915. #ifdef CLOCK_MONOTONIC
  916. if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
  917. #else
  918. if (clock_gettime(CLOCK_REALTIME, &ts) == -1)
  919. #endif
  920. event_err(1, "clock_gettime");
  921. trans_id = ts.tv_nsec & 0xffff;
  922. #endif
  923. #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
  924. struct timeval tv;
  925. u16 trans_id;
  926. gettimeofday(&tv, NULL);
  927. trans_id = tv.tv_usec & 0xffff;
  928. #endif
  929. #ifdef DNS_USE_OPENSSL_FOR_ID
  930. u16 trans_id;
  931. if (RAND_pseudo_bytes((u8 *) &trans_id, 2) == -1) {
  932. /* in the case that the RAND call fails we back */
  933. /* down to using gettimeofday. */
  934. /*
  935. struct timeval tv;
  936. gettimeofday(&tv, NULL);
  937. trans_id = tv.tv_usec & 0xffff;
  938. */
  939. abort();
  940. }
  941. #endif
  942. if (trans_id == 0xffff) continue;
  943. /* now check to see if that id is already inflight */
  944. req = started_at = req_head;
  945. if (req) {
  946. do {
  947. if (req->trans_id == trans_id) break;
  948. req = req->next;
  949. } while (req != started_at);
  950. }
  951. /* we didn't find it, so this is a good id */
  952. if (req == started_at) return trans_id;
  953. }
  954. }
  955. /* choose a namesever to use. This function will try to ignore */
  956. /* nameservers which we think are down and load balance across the rest */
  957. /* by updating the server_head global each time. */
  958. static struct nameserver *
  959. nameserver_pick(void) {
  960. struct nameserver *started_at = server_head, *picked;
  961. if (!server_head) return NULL;
  962. /* if we don't have any good nameservers then there's no */
  963. /* point in trying to find one. */
  964. if (!global_good_nameservers) {
  965. server_head = server_head->next;
  966. return server_head;
  967. }
  968. /* remember that nameservers are in a circular list */
  969. for (;;) {
  970. if (server_head->state) {
  971. /* we think this server is currently good */
  972. picked = server_head;
  973. server_head = server_head->next;
  974. return picked;
  975. }
  976. server_head = server_head->next;
  977. if (server_head == started_at) {
  978. /* all the nameservers seem to be down */
  979. /* so we just return this one and hope for the */
  980. /* best */
  981. assert(global_good_nameservers == 0);
  982. picked = server_head;
  983. server_head = server_head->next;
  984. return picked;
  985. }
  986. }
  987. }
  988. /* this is called when a namesever socket is ready for reading */
  989. static void
  990. nameserver_read(struct nameserver *ns) {
  991. u8 packet[1500];
  992. for (;;) {
  993. const int r = recv(ns->socket, packet, sizeof(packet), 0);
  994. if (r < 0) {
  995. int err = last_error(ns->socket);
  996. if (error_is_eagain(err)) return;
  997. nameserver_failed(ns, strerror(err));
  998. return;
  999. }
  1000. ns->timedout = 0;
  1001. reply_parse(packet, r);
  1002. }
  1003. }
  1004. /* Read a packet from a DNS client on a server port s, parse it, and */
  1005. /* act accordingly. */
  1006. static void
  1007. server_port_read(struct evdns_server_port *s) {
  1008. u8 packet[1500];
  1009. struct sockaddr_storage addr;
  1010. socklen_t addrlen;
  1011. int r;
  1012. for (;;) {
  1013. addrlen = sizeof(struct sockaddr_storage);
  1014. r = recvfrom(s->socket, packet, sizeof(packet), 0,
  1015. (struct sockaddr*) &addr, &addrlen);
  1016. if (r < 0) {
  1017. int err = last_error(s->socket);
  1018. if (error_is_eagain(err)) return;
  1019. log(EVDNS_LOG_WARN, "Error %s (%d) while reading request.",
  1020. strerror(err), err);
  1021. return;
  1022. }
  1023. request_parse(packet, r, s, (struct sockaddr*) &addr, addrlen);
  1024. }
  1025. }
  1026. /* Try to write all pending replies on a given DNS server port. */
  1027. static void
  1028. server_port_flush(struct evdns_server_port *port)
  1029. {
  1030. while (port->pending_replies) {
  1031. struct server_request *req = port->pending_replies;
  1032. int r = sendto(port->socket, req->response, req->response_len, 0,
  1033. (struct sockaddr*) &req->addr, req->addrlen);
  1034. if (r < 0) {
  1035. int err = last_error(port->socket);
  1036. if (error_is_eagain(err))
  1037. return;
  1038. log(EVDNS_LOG_WARN, "Error %s (%d) while writing response to port; dropping", strerror(err), err);
  1039. }
  1040. if (server_request_free(req)) {
  1041. /* we released the last reference to req->port. */
  1042. return;
  1043. }
  1044. }
  1045. /* We have no more pending requests; stop listening for 'writeable' events. */
  1046. (void) event_del(&port->event);
  1047. CLEAR(&port->event);
  1048. event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
  1049. server_port_ready_callback, port);
  1050. if (event_add(&port->event, NULL) < 0) {
  1051. log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server.");
  1052. /* ???? Do more? */
  1053. }
  1054. }
  1055. /* set if we are waiting for the ability to write to this server. */
  1056. /* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
  1057. /* we stop these events. */
  1058. static void
  1059. nameserver_write_waiting(struct nameserver *ns, char waiting) {
  1060. if (ns->write_waiting == waiting) return;
  1061. ns->write_waiting = waiting;
  1062. (void) event_del(&ns->event);
  1063. CLEAR(&ns->event);
  1064. event_set(&ns->event, ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
  1065. nameserver_ready_callback, ns);
  1066. if (event_add(&ns->event, NULL) < 0) {
  1067. log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s",
  1068. debug_ntoa(ns->address));
  1069. /* ???? Do more? */
  1070. }
  1071. }
  1072. /* a callback function. Called by libevent when the kernel says that */
  1073. /* a nameserver socket is ready for writing or reading */
  1074. static void
  1075. nameserver_ready_callback(int fd, short events, void *arg) {
  1076. struct nameserver *ns = (struct nameserver *) arg;
  1077. (void)fd;
  1078. if (events & EV_WRITE) {
  1079. ns->choked = 0;
  1080. if (!evdns_transmit()) {
  1081. nameserver_write_waiting(ns, 0);
  1082. }
  1083. }
  1084. if (events & EV_READ) {
  1085. nameserver_read(ns);
  1086. }
  1087. }
  1088. /* a callback function. Called by libevent when the kernel says that */
  1089. /* a server socket is ready for writing or reading. */
  1090. static void
  1091. server_port_ready_callback(int fd, short events, void *arg) {
  1092. struct evdns_server_port *port = (struct evdns_server_port *) arg;
  1093. (void) fd;
  1094. if (events & EV_WRITE) {
  1095. port->choked = 0;
  1096. server_port_flush(port);
  1097. }
  1098. if (events & EV_READ) {
  1099. server_port_read(port);
  1100. }
  1101. }
  1102. /* This is an inefficient representation; only use it via the dnslabel_table_*
  1103. * functions, so that is can be safely replaced with something smarter later. */
  1104. #define MAX_LABELS 128
  1105. /* Structures used to implement name compression */
  1106. struct dnslabel_entry { char *v; off_t pos; };
  1107. struct dnslabel_table {
  1108. int n_labels; /* number of current entries */
  1109. /* map from name to position in message */
  1110. struct dnslabel_entry labels[MAX_LABELS];
  1111. };
  1112. /* Initialize dnslabel_table. */
  1113. static void
  1114. dnslabel_table_init(struct dnslabel_table *table)
  1115. {
  1116. table->n_labels = 0;
  1117. }
  1118. /* Free all storage held by table, but not the table itself. */
  1119. static void
  1120. dnslabel_clear(struct dnslabel_table *table)
  1121. {
  1122. int i;
  1123. for (i = 0; i < table->n_labels; ++i)
  1124. free(table->labels[i].v);
  1125. table->n_labels = 0;
  1126. }
  1127. /* return the position of the label in the current message, or -1 if the label */
  1128. /* hasn't been used yet. */
  1129. static int
  1130. dnslabel_table_get_pos(const struct dnslabel_table *table, const char *label)
  1131. {
  1132. int i;
  1133. for (i = 0; i < table->n_labels; ++i) {
  1134. if (!strcmp(label, table->labels[i].v))
  1135. return table->labels[i].pos;
  1136. }
  1137. return -1;
  1138. }
  1139. /* remember that we've used the label at position pos */
  1140. static int
  1141. dnslabel_table_add(struct dnslabel_table *table, const char *label, off_t pos)
  1142. {
  1143. char *v;
  1144. int p;
  1145. if (table->n_labels == MAX_LABELS)
  1146. return (-1);
  1147. v = strdup(label);
  1148. if (v == NULL)
  1149. return (-1);
  1150. p = table->n_labels++;
  1151. table->labels[p].v = v;
  1152. table->labels[p].pos = pos;
  1153. return (0);
  1154. }
  1155. /* Converts a string to a length-prefixed set of DNS labels, starting */
  1156. /* at buf[j]. name and buf must not overlap. name_len should be the length */
  1157. /* of name. table is optional, and is used for compression. */
  1158. /* */
  1159. /* Input: abc.def */
  1160. /* Output: <3>abc<3>def<0> */
  1161. /* */
  1162. /* Returns the first index after the encoded name, or negative on error. */
  1163. /* -1 label was > 63 bytes */
  1164. /* -2 name too long to fit in buffer. */
  1165. /* */
  1166. static off_t
  1167. dnsname_to_labels(u8 *const buf, size_t buf_len, off_t j,
  1168. const char *name, const int name_len,
  1169. struct dnslabel_table *table) {
  1170. const char *end = name + name_len;
  1171. int ref = 0;
  1172. u16 _t;
  1173. #define APPEND16(x) do { \
  1174. if (j + 2 > (off_t)buf_len) \
  1175. goto overflow; \
  1176. _t = htons(x); \
  1177. memcpy(buf + j, &_t, 2); \
  1178. j += 2; \
  1179. } while (0)
  1180. #define APPEND32(x) do { \
  1181. if (j + 4 > (off_t)buf_len) \
  1182. goto overflow; \
  1183. _t32 = htonl(x); \
  1184. memcpy(buf + j, &_t32, 4); \
  1185. j += 4; \
  1186. } while (0)
  1187. if (name_len > 255) return -2;
  1188. for (;;) {
  1189. const char *const start = name;
  1190. if (table && (ref = dnslabel_table_get_pos(table, name)) >= 0) {
  1191. APPEND16(ref | 0xc000);
  1192. return j;
  1193. }
  1194. name = strchr(name, '.');
  1195. if (!name) {
  1196. const unsigned int label_len = end - start;
  1197. if (label_len > 63) return -1;
  1198. if ((size_t)(j+label_len+1) > buf_len) return -2;
  1199. if (table) dnslabel_table_add(table, start, j);
  1200. buf[j++] = label_len;
  1201. memcpy(buf + j, start, end - start);
  1202. j += end - start;
  1203. break;
  1204. } else {
  1205. /* append length of the label. */
  1206. const unsigned int label_len = name - start;
  1207. if (label_len > 63) return -1;
  1208. if ((size_t)(j+label_len+1) > buf_len) return -2;
  1209. if (table) dnslabel_table_add(table, start, j);
  1210. buf[j++] = label_len;
  1211. memcpy(buf + j, start, name - start);
  1212. j += name - start;
  1213. /* hop over the '.' */
  1214. name++;
  1215. }
  1216. }
  1217. /* the labels must be terminated by a 0. */
  1218. /* It's possible that the name ended in a . */
  1219. /* in which case the zero is already there */
  1220. if (!j || buf[j-1]) buf[j++] = 0;
  1221. return j;
  1222. overflow:
  1223. return (-2);
  1224. }
  1225. /* Finds the length of a dns request for a DNS name of the given */
  1226. /* length. The actual request may be smaller than the value returned */
  1227. /* here */
  1228. static int
  1229. evdns_request_len(const int name_len) {
  1230. return 96 + /* length of the DNS standard header */
  1231. name_len + 2 +
  1232. 4; /* space for the resource type */
  1233. }
  1234. /* build a dns request packet into buf. buf should be at least as long */
  1235. /* as evdns_request_len told you it should be. */
  1236. /* */
  1237. /* Returns the amount of space used. Negative on error. */
  1238. static int
  1239. evdns_request_data_build(const char *const name, const int name_len,
  1240. const u16 trans_id, const u16 type, const u16 class,
  1241. u8 *const buf, size_t buf_len) {
  1242. off_t j = 0; /* current offset into buf */
  1243. u16 _t; /* used by the macros */
  1244. APPEND16(trans_id);
  1245. APPEND16(0x0100); /* standard query, recusion needed */
  1246. APPEND16(1); /* one question */
  1247. APPEND16(0); /* no answers */
  1248. APPEND16(0); /* no authority */
  1249. APPEND16(0); /* no additional */
  1250. j = dnsname_to_labels(buf, buf_len, j, name, name_len, NULL);
  1251. if (j < 0) {
  1252. return (int)j;
  1253. }
  1254. APPEND16(type);
  1255. APPEND16(class);
  1256. return (int)j;
  1257. overflow:
  1258. return (-1);
  1259. }
  1260. /* exported function */
  1261. struct evdns_server_port *
  1262. evdns_add_server_port(int socket, int is_tcp, evdns_request_callback_fn_type cb, void *user_data)
  1263. {
  1264. struct evdns_server_port *port;
  1265. if (!(port = malloc(sizeof(struct evdns_server_port))))
  1266. return NULL;
  1267. memset(port, 0, sizeof(struct evdns_server_port));
  1268. assert(!is_tcp); /* TCP sockets not yet implemented */
  1269. port->socket = socket;
  1270. port->refcnt = 1;
  1271. port->choked = 0;
  1272. port->closing = 0;
  1273. port->user_callback = cb;
  1274. port->user_data = user_data;
  1275. port->pending_replies = NULL;
  1276. event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
  1277. server_port_ready_callback, port);
  1278. event_add(&port->event, NULL); /* check return. */
  1279. return port;
  1280. }
  1281. /* exported function */
  1282. void
  1283. evdns_close_server_port(struct evdns_server_port *port)
  1284. {
  1285. if (--port->refcnt == 0)
  1286. server_port_free(port);
  1287. port->closing = 1;
  1288. }
  1289. /* exported function */
  1290. int
  1291. evdns_server_request_add_reply(struct evdns_server_request *_req, int section, const char *name, int type, int class, int ttl, int datalen, int is_name, const char *data)
  1292. {
  1293. struct server_request *req = TO_SERVER_REQUEST(_req);
  1294. struct server_reply_item **itemp, *item;
  1295. int *countp;
  1296. if (req->response) /* have we already answered? */
  1297. return (-1);
  1298. switch (section) {
  1299. case EVDNS_ANSWER_SECTION:
  1300. itemp = &req->answer;
  1301. countp = &req->n_answer;
  1302. break;
  1303. case EVDNS_AUTHORITY_SECTION:
  1304. itemp = &req->authority;
  1305. countp = &req->n_authority;
  1306. break;
  1307. case EVDNS_ADDITIONAL_SECTION:
  1308. itemp = &req->additional;
  1309. countp = &req->n_additional;
  1310. break;
  1311. default:
  1312. return (-1);
  1313. }
  1314. while (*itemp) {
  1315. itemp = &((*itemp)->next);
  1316. }
  1317. item = malloc(sizeof(struct server_reply_item));
  1318. if (!item)
  1319. return -1;
  1320. CLEAR(item);
  1321. item->next = NULL;
  1322. if (!(item->name = strdup(name))) {
  1323. CLEAR(item);
  1324. free(item);
  1325. return -1;
  1326. }
  1327. item->type = type;
  1328. item->class = class;
  1329. item->ttl = ttl;
  1330. item->is_name = is_name != 0;
  1331. item->datalen = 0;
  1332. item->data = NULL;
  1333. if (data) {
  1334. if (item->is_name) {
  1335. if (!(item->data = strdup(data))) {
  1336. free(item->name);
  1337. CLEAR(item);
  1338. free(item);
  1339. return -1;
  1340. }
  1341. item->datalen = (u16)-1;
  1342. } else {
  1343. if (!(item->data = malloc(datalen))) {
  1344. free(item->name);
  1345. CLEAR(item);
  1346. free(item);
  1347. return -1;
  1348. }
  1349. item->datalen = datalen;
  1350. memcpy(item->data, data, datalen);
  1351. }
  1352. }
  1353. *itemp = item;
  1354. ++(*countp);
  1355. return 0;
  1356. }
  1357. /* exported function */
  1358. int
  1359. evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl)
  1360. {
  1361. return evdns_server_request_add_reply(
  1362. req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
  1363. ttl, n*4, 0, addrs);
  1364. }
  1365. /* exported function */
  1366. int
  1367. evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl)
  1368. {
  1369. return evdns_server_request_add_reply(
  1370. req, EVDNS_ANSWER_SECTION, name, TYPE_AAAA, CLASS_INET,
  1371. ttl, n*16, 0, addrs);
  1372. }
  1373. /* exported function */
  1374. int
  1375. evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl)
  1376. {
  1377. u32 a;
  1378. char buf[32];
  1379. assert(in || inaddr_name);
  1380. assert(!(in && inaddr_name));
  1381. if (in) {
  1382. a = ntohl(in->s_addr);
  1383. snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
  1384. (int)(u8)((a )&0xff),
  1385. (int)(u8)((a>>8 )&0xff),
  1386. (int)(u8)((a>>16)&0xff),
  1387. (int)(u8)((a>>24)&0xff));
  1388. inaddr_name = buf;
  1389. }
  1390. return evdns_server_request_add_reply(
  1391. req, EVDNS_ANSWER_SECTION, inaddr_name, TYPE_PTR, CLASS_INET,
  1392. ttl, -1, 1, hostname);
  1393. }
  1394. /* exported function */
  1395. int
  1396. evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl)
  1397. {
  1398. return evdns_server_request_add_reply(
  1399. req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
  1400. ttl, -1, 1, cname);
  1401. }
  1402. static int
  1403. evdns_server_request_format_response(struct server_request *req, int err)
  1404. {
  1405. unsigned char buf[1500];
  1406. size_t buf_len = sizeof(buf);
  1407. off_t j = 0, r;
  1408. u16 _t;
  1409. u32 _t32;
  1410. int i;
  1411. u16 flags;
  1412. struct dnslabel_table table;
  1413. if (err < 0 || err > 15) return -1;
  1414. /* Set response bit and error code; copy OPCODE and RD fields from
  1415. * question; copy RA and AA if set by caller. */
  1416. flags = req->base.flags;
  1417. flags |= (0x8000 | err);
  1418. dnslabel_table_init(&table);
  1419. APPEND16(req->trans_id);
  1420. APPEND16(flags);
  1421. APPEND16(req->base.nquestions);
  1422. APPEND16(req->n_answer);
  1423. APPEND16(req->n_authority);
  1424. APPEND16(req->n_additional);
  1425. /* Add questions. */
  1426. for (i=0; i < req->base.nquestions; ++i) {
  1427. const char *s = req->base.questions[i]->name;
  1428. j = dnsname_to_labels(buf, buf_len, j, s, strlen(s), &table);
  1429. if (j < 0) {
  1430. dnslabel_clear(&table);
  1431. return (int) j;
  1432. }
  1433. APPEND16(req->base.questions[i]->type);
  1434. APPEND16(req->base.questions[i]->class);
  1435. }
  1436. /* Add answer, authority, and additional sections. */
  1437. for (i=0; i<3; ++i) {
  1438. struct server_reply_item *item;
  1439. if (i==0)
  1440. item = req->answer;
  1441. else if (i==1)
  1442. item = req->authority;
  1443. else
  1444. item = req->additional;
  1445. while (item) {
  1446. r = dnsname_to_labels(buf, buf_len, j, item->name, strlen(item->name), &table);
  1447. if (r < 0)
  1448. goto overflow;
  1449. j = r;
  1450. APPEND16(item->type);
  1451. APPEND16(item->class);
  1452. APPEND32(item->ttl);
  1453. if (item->is_name) {
  1454. off_t len_idx = j, name_start;
  1455. j += 2;
  1456. name_start = j;
  1457. r = dnsname_to_labels(buf, buf_len, j, item->data, strlen(item->data), &table);
  1458. if (r < 0)
  1459. goto overflow;
  1460. j = r;
  1461. _t = htons( (j-name_start) );
  1462. memcpy(buf+len_idx, &_t, 2);
  1463. } else {
  1464. APPEND16(item->datalen);
  1465. if (j+item->datalen > (off_t)buf_len)
  1466. goto overflow;
  1467. memcpy(buf+j, item->data, item->datalen);
  1468. j += item->datalen;
  1469. }
  1470. item = item->next;
  1471. }
  1472. }
  1473. if (j > 512) {
  1474. overflow:
  1475. j = 512;
  1476. buf[3] |= 0x02; /* set the truncated bit. */
  1477. }
  1478. req->response_len = j;
  1479. if (!(req->response = malloc(req->response_len))) {
  1480. server_request_free_answers(req);
  1481. dnslabel_clear(&table);
  1482. return (-1);
  1483. }
  1484. memcpy(req->response, buf, req->response_len);
  1485. server_request_free_answers(req);
  1486. dnslabel_clear(&table);
  1487. return (0);
  1488. }
  1489. /* exported function */
  1490. int
  1491. evdns_server_request_respond(struct evdns_server_request *_req, int err)
  1492. {
  1493. struct server_request *req = TO_SERVER_REQUEST(_req);
  1494. struct evdns_server_port *port = req->port;
  1495. int r;
  1496. if (!req->response) {
  1497. if ((r = evdns_server_request_format_response(req, err))<0)
  1498. return r;
  1499. }
  1500. r = sendto(port->socket, req->response, req->response_len, 0,
  1501. (struct sockaddr*) &req->addr, req->addrlen);
  1502. if (r<0) {
  1503. int e = last_error(port->socket);
  1504. if (! error_is_eagain(e))
  1505. return -1;
  1506. if (port->pending_replies) {
  1507. req->prev_pending = port->pending_replies->prev_pending;
  1508. req->next_pending = port->pending_replies;
  1509. req->prev_pending->next_pending =
  1510. req->next_pending->prev_pending = req;
  1511. } else {
  1512. req->prev_pending = req->next_pending = req;
  1513. port->pending_replies = req;
  1514. port->choked = 1;
  1515. (void) event_del(&port->event);
  1516. CLEAR(&port->event);
  1517. event_set(&port->event, port->socket, (port->closing?0:EV_READ) | EV_WRITE | EV_PERSIST, server_port_ready_callback, port);
  1518. if (event_add(&port->event, NULL) < 0) {
  1519. log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server");
  1520. }
  1521. }
  1522. return 1;
  1523. }
  1524. if (server_request_free(req))
  1525. return 0;
  1526. if (port->pending_replies)
  1527. server_port_flush(port);
  1528. return 0;
  1529. }
  1530. /* Free all storage held by RRs in req. */
  1531. static void
  1532. server_request_free_answers(struct server_request *req)
  1533. {
  1534. struct server_reply_item *victim, *next, **list;
  1535. int i;
  1536. for (i = 0; i < 3; ++i) {
  1537. if (i==0)
  1538. list = &req->answer;
  1539. else if (i==1)
  1540. list = &req->authority;
  1541. else
  1542. list = &req->additional;
  1543. victim = *list;
  1544. while (victim) {
  1545. next = victim->next;
  1546. free(victim->name);
  1547. if (victim->data)
  1548. free(victim->data);
  1549. free(victim);
  1550. victim = next;
  1551. }
  1552. *list = NULL;
  1553. }
  1554. }
  1555. /* Free all storage held by req, and remove links to it. */
  1556. /* return true iff we just wound up freeing the server_port. */
  1557. static int
  1558. server_request_free(struct server_request *req)
  1559. {
  1560. int i, rc=1;
  1561. if (req->base.questions) {
  1562. for (i = 0; i < req->base.nquestions; ++i)
  1563. free(req->base.questions[i]);
  1564. free(req->base.questions);
  1565. }
  1566. if (req->port) {
  1567. if (req->port->pending_replies == req) {
  1568. if (req->next_pending)
  1569. req->port->pending_replies = req->next_pending;
  1570. else
  1571. req->port->pending_replies = NULL;
  1572. }
  1573. rc = --req->port->refcnt;
  1574. }
  1575. if (req->response) {
  1576. free(req->response);
  1577. }
  1578. server_request_free_answers(req);
  1579. if (req->next_pending && req->next_pending != req) {
  1580. req->next_pending->prev_pending = req->prev_pending;
  1581. req->prev_pending->next_pending = req->next_pending;
  1582. }
  1583. if (rc == 0) {
  1584. server_port_free(req->port);
  1585. CLEAR(req);
  1586. free(req);
  1587. return (1);
  1588. }
  1589. CLEAR(req);
  1590. free(req);
  1591. return (0);
  1592. }
  1593. /* Free all storage held by an evdns_server_port. Only called when */
  1594. static void
  1595. server_port_free(struct evdns_server_port *port)
  1596. {
  1597. assert(port);
  1598. assert(!port->refcnt);
  1599. assert(!port->pending_replies);
  1600. if (port->socket > 0) {
  1601. CLOSE_SOCKET(port->socket);
  1602. port->socket = -1;
  1603. }
  1604. (void) event_del(&port->event);
  1605. CLEAR(&port->event);
  1606. /* XXXX020 actually free the port? -NM */
  1607. /* XXXX yes, and fix up evdns_close_server_port to dtrt. -NM */
  1608. }
  1609. /* exported function */
  1610. int
  1611. evdns_server_request_drop(struct evdns_server_request *_req)
  1612. {
  1613. struct server_request *req = TO_SERVER_REQUEST(_req);
  1614. server_request_free(req);
  1615. return 0;
  1616. }
  1617. /* exported function */
  1618. int
  1619. evdns_server_request_get_requesting_addr(struct evdns_server_request *_req, struct sockaddr *sa, int addr_len)
  1620. {
  1621. struct server_request *req = TO_SERVER_REQUEST(_req);
  1622. if (addr_len < (int)req->addrlen)
  1623. return -1;
  1624. memcpy(sa, &(req->addr), req->addrlen);
  1625. return req->addrlen;
  1626. }
  1627. #undef APPEND16
  1628. #undef APPEND32
  1629. /* this is a libevent callback function which is called when a request */
  1630. /* has timed out. */
  1631. static void
  1632. evdns_request_timeout_callback(int fd, short events, void *arg) {
  1633. struct request *const req = (struct request *) arg;
  1634. (void) fd;
  1635. (void) events;
  1636. log(EVDNS_LOG_DEBUG, "Request %lx timed out", (unsigned long) arg);
  1637. req->ns->timedout++;
  1638. if (req->ns->timedout > global_max_nameserver_timeout) {
  1639. req->ns->timedout = 0;
  1640. nameserver_failed(req->ns, "request timed out.");
  1641. }
  1642. (void) evtimer_del(&req->timeout_event);
  1643. CLEAR(&req->timeout_event);
  1644. if (req->tx_count >= global_max_retransmits) {
  1645. /* this request has failed */
  1646. reply_callback(req, 0, DNS_ERR_TIMEOUT, NULL);
  1647. request_finished(req, &req_head);
  1648. } else {
  1649. /* retransmit it */
  1650. evdns_request_transmit(req);
  1651. }
  1652. }
  1653. /* try to send a request to a given server. */
  1654. /* */
  1655. /* return: */
  1656. /* 0 ok */
  1657. /* 1 temporary failure */
  1658. /* 2 other failure */
  1659. static int
  1660. evdns_request_transmit_to(struct request *req, struct nameserver *server) {
  1661. const int r = send(server->socket, req->request, req->request_len, 0);
  1662. if (r < 0) {
  1663. int e = last_error(server->socket);
  1664. if (error_is_eagain(e)) return 1;
  1665. nameserver_failed(req->ns, strerror(e));
  1666. return 2;
  1667. } else if (r != (int)req->request_len) {
  1668. return 1; /* short write */
  1669. } else {
  1670. return 0;
  1671. }
  1672. }
  1673. /* try to send a request, updating the fields of the request */
  1674. /* as needed */
  1675. /* */
  1676. /* return: */
  1677. /* 0 ok */
  1678. /* 1 failed */
  1679. static int
  1680. evdns_request_transmit(struct request *req) {
  1681. int retcode = 0, r;
  1682. /* if we fail to send this packet then this flag marks it */
  1683. /* for evdns_transmit */
  1684. req->transmit_me = 1;
  1685. if (req->trans_id == 0xffff) abort();
  1686. if (req->ns->choked) {
  1687. /* don't bother trying to write to a socket */
  1688. /* which we have had EAGAIN from */
  1689. return 1;
  1690. }
  1691. r = evdns_request_transmit_to(req, req->ns);
  1692. switch (r) {
  1693. case 1:
  1694. /* temp failure */
  1695. req->ns->choked = 1;
  1696. nameserver_write_waiting(req->ns, 1);
  1697. return 1;
  1698. case 2:
  1699. /* failed in some other way */
  1700. retcode = 1;
  1701. break;
  1702. default:
  1703. /* transmitted; we need to check for timeout. */
  1704. log(EVDNS_LOG_DEBUG,
  1705. "Setting timeout for request %lx", (unsigned long) req);
  1706. evtimer_set(&req->timeout_event, evdns_request_timeout_callback, req);
  1707. if (evtimer_add(&req->timeout_event, &global_timeout) < 0) {
  1708. log(EVDNS_LOG_WARN,
  1709. "Error from libevent when adding timer for request %lx",
  1710. (unsigned long) req);
  1711. /* ???? Do more? */
  1712. }
  1713. }
  1714. req->tx_count++;
  1715. req->transmit_me = 0;
  1716. return retcode;
  1717. }
  1718. static void
  1719. nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) {
  1720. struct nameserver *const ns = (struct nameserver *) arg;
  1721. (void) type;
  1722. (void) count;
  1723. (void) ttl;
  1724. (void) addresses;
  1725. if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
  1726. /* this is a good reply */
  1727. nameserver_up(ns);
  1728. } else nameserver_probe_failed(ns);
  1729. }
  1730. static void
  1731. nameserver_send_probe(struct nameserver *const ns) {
  1732. struct request *req;
  1733. /* here we need to send a probe to a given nameserver */
  1734. /* in the hope that it is up now. */
  1735. log(EVDNS_LOG_DEBUG, "Sending probe to %s", debug_ntoa(ns->address));
  1736. req = request_new(TYPE_A, "www.google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, ns);
  1737. if (!req) return;
  1738. /* we force this into the inflight queue no matter what */
  1739. request_trans_id_set(req, transaction_id_pick());
  1740. req->ns = ns;
  1741. request_submit(req);
  1742. }
  1743. /* returns: */
  1744. /* 0 didn't try to transmit anything */
  1745. /* 1 tried to transmit something */
  1746. static int
  1747. evdns_transmit(void) {
  1748. char did_try_to_transmit = 0;
  1749. if (req_head) {
  1750. struct request *const started_at = req_head, *req = req_head;
  1751. /* first transmit all the requests which are currently waiting */
  1752. do {
  1753. if (req->transmit_me) {
  1754. did_try_to_transmit = 1;
  1755. evdns_request_transmit(req);
  1756. }
  1757. req = req->next;
  1758. } while (req != started_at);
  1759. }
  1760. return did_try_to_transmit;
  1761. }
  1762. /* exported function */
  1763. int
  1764. evdns_count_nameservers(void)
  1765. {
  1766. const struct nameserver *server = server_head;
  1767. int n = 0;
  1768. if (!server)
  1769. return 0;
  1770. do {
  1771. ++n;
  1772. server = server->next;
  1773. } while (server != server_head);
  1774. return n;
  1775. }
  1776. /* exported function */
  1777. int
  1778. evdns_clear_nameservers_and_suspend(void)
  1779. {
  1780. struct nameserver *server = server_head, *started_at = server_head;
  1781. struct request *req = req_head, *req_started_at = req_head;
  1782. if (!server)
  1783. return 0;
  1784. while (1) {
  1785. struct nameserver *next = server->next;
  1786. (void) event_del(&server->event);
  1787. CLEAR(&server->event);
  1788. (void) evtimer_del(&server->timeout_event);
  1789. CLEAR(&server->timeout_event);
  1790. if (server->socket >= 0)
  1791. CLOSE_SOCKET(server->socket);
  1792. CLEAR(server);
  1793. free(server);
  1794. if (next == started_at)
  1795. break;
  1796. server = next;
  1797. }
  1798. server_head = NULL;
  1799. global_good_nameservers = 0;
  1800. while (req) {
  1801. struct request *next = req->next;
  1802. req->tx_count = req->reissue_count = 0;
  1803. req->ns = NULL;
  1804. /* ???? What to do about searches? */
  1805. (void) evtimer_del(&req->timeout_event);
  1806. CLEAR(&req->timeout_event);
  1807. req->trans_id = 0;
  1808. req->transmit_me = 0;
  1809. global_requests_waiting++;
  1810. evdns_request_insert(req, &req_waiting_head);
  1811. /* We want to insert these suspended elements at the front of
  1812. * the waiting queue, since they were pending before any of
  1813. * the waiting entries were added. This is a circular list,
  1814. * so we can just shift the start back by one.*/
  1815. req_waiting_head = req_waiting_head->prev;
  1816. if (next == req_started_at)
  1817. break;
  1818. req = next;
  1819. }
  1820. req_head = NULL;
  1821. global_requests_inflight = 0;
  1822. return 0;
  1823. }
  1824. /* exported function */
  1825. int
  1826. evdns_resume(void)
  1827. {
  1828. evdns_requests_pump_waiting_queue();
  1829. return 0;
  1830. }
  1831. static int
  1832. _evdns_nameserver_add_impl(unsigned long int address, int port) {
  1833. /* first check to see if we already have this nameserver */
  1834. const struct nameserver *server = server_head, *const started_at = server_head;
  1835. struct nameserver *ns;
  1836. struct sockaddr_in sin;
  1837. int err = 0;
  1838. if (server) {
  1839. do {
  1840. if (server->address == address) return 3;
  1841. server = server->next;
  1842. } while (server != started_at);
  1843. }
  1844. ns = (struct nameserver *) malloc(sizeof(struct nameserver));
  1845. if (!ns) return -1;
  1846. memset(ns, 0, sizeof(struct nameserver));
  1847. ns->socket = socket(PF_INET, SOCK_DGRAM, 0);
  1848. if (ns->socket < 0) { err = 1; goto out1; }
  1849. #ifdef WIN32
  1850. {
  1851. u_long nonblocking = 1;
  1852. ioctlsocket(ns->socket, FIONBIO, &nonblocking);
  1853. }
  1854. #else
  1855. fcntl(ns->socket, F_SETFL, O_NONBLOCK);
  1856. #endif
  1857. sin.sin_addr.s_addr = address;
  1858. sin.sin_port = htons(port);
  1859. sin.sin_family = AF_INET;
  1860. if (connect(ns->socket, (struct sockaddr *) &sin, sizeof(sin)) != 0) {
  1861. err = 2;
  1862. goto out2;
  1863. }
  1864. ns->address = address;
  1865. ns->state = 1;
  1866. event_set(&ns->event, ns->socket, EV_READ | EV_PERSIST, nameserver_ready_callback, ns);
  1867. if (event_add(&ns->event, NULL) < 0) {
  1868. err = 2;
  1869. goto out2;
  1870. }
  1871. log(EVDNS_LOG_DEBUG, "Added nameserver %s", debug_ntoa(address));
  1872. /* insert this nameserver into the list of them */
  1873. if (!server_head) {
  1874. ns->next = ns->prev = ns;
  1875. server_head = ns;
  1876. } else {
  1877. ns->next = server_head->next;
  1878. ns->prev = server_head;
  1879. server_head->next = ns;
  1880. if (server_head->prev == server_head) {
  1881. server_head->prev = ns;
  1882. }
  1883. }
  1884. global_good_nameservers++;
  1885. return 0;
  1886. out2:
  1887. CLOSE_SOCKET(ns->socket);
  1888. out1:
  1889. CLEAR(ns);
  1890. free(ns);
  1891. log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d", debug_ntoa(address), err);
  1892. return err;
  1893. }
  1894. /* exported function */
  1895. int
  1896. evdns_nameserver_add(unsigned long int address) {
  1897. return _evdns_nameserver_add_impl(address, 53);
  1898. }
  1899. /* exported function */
  1900. int
  1901. evdns_nameserver_ip_add(const char *ip_as_string) {
  1902. struct in_addr ina;
  1903. int port;
  1904. char buf[20];
  1905. const char *cp;
  1906. cp = strchr(ip_as_string, ':');
  1907. if (! cp) {
  1908. cp = ip_as_string;
  1909. port = 53;
  1910. } else {
  1911. port = strtoint(cp+1);
  1912. if (port < 0 || port > 65535) {
  1913. return 4;
  1914. }
  1915. if ((cp-ip_as_string) >= (int)sizeof(buf)) {
  1916. return 4;
  1917. }
  1918. memcpy(buf, ip_as_string, cp-ip_as_string);
  1919. buf[cp-ip_as_string] = '\0';
  1920. cp = buf;
  1921. }
  1922. if (!inet_aton(cp, &ina)) {
  1923. return 4;
  1924. }
  1925. return _evdns_nameserver_add_impl(ina.s_addr, port);
  1926. }
  1927. /* insert into the tail of the queue */
  1928. static void
  1929. evdns_request_insert(struct request *req, struct request **head) {
  1930. if (!*head) {
  1931. *head = req;
  1932. req->next = req->prev = req;
  1933. return;
  1934. }
  1935. req->prev = (*head)->prev;
  1936. req->prev->next = req;
  1937. req->next = *head;
  1938. (*head)->prev = req;
  1939. }
  1940. static int
  1941. string_num_dots(const char *s) {
  1942. int count = 0;
  1943. while ((s = strchr(s, '.'))) {
  1944. s++;
  1945. count++;
  1946. }
  1947. return count;
  1948. }
  1949. static struct request *
  1950. request_new(int type, const char *name, int flags,
  1951. evdns_callback_type callback, void *user_ptr) {
  1952. const char issuing_now =
  1953. (global_requests_inflight < global_max_requests_inflight) ? 1 : 0;
  1954. const int name_len = strlen(name);
  1955. const int request_max_len = evdns_request_len(name_len);
  1956. const u16 trans_id = issuing_now ? transaction_id_pick() : 0xffff;
  1957. /* the request data is alloced in a single block with the header */
  1958. struct request *const req =
  1959. (struct request *) malloc(sizeof(struct request) + request_max_len);
  1960. int rlen;
  1961. (void) flags;
  1962. if (!req) return NULL;
  1963. memset(req, 0, sizeof(struct request));
  1964. /* request data lives just after the header */
  1965. req->request = ((u8 *) req) + sizeof(struct request);
  1966. /* denotes that the request data shouldn't be free()ed */
  1967. req->request_appended = 1;
  1968. rlen = evdns_request_data_build(name, name_len, trans_id,
  1969. type, CLASS_INET, req->request, request_max_len);
  1970. if (rlen < 0)
  1971. goto err1;
  1972. req->request_len = rlen;
  1973. req->trans_id = trans_id;
  1974. req->tx_count = 0;
  1975. req->request_type = type;
  1976. req->user_pointer = user_ptr;
  1977. req->user_callback = callback;
  1978. req->ns = issuing_now ? nameserver_pick() : NULL;
  1979. req->next = req->prev = NULL;
  1980. return req;
  1981. err1:
  1982. CLEAR(req);
  1983. _free(req);
  1984. return NULL;
  1985. }
  1986. static void
  1987. request_submit(struct request *const req) {
  1988. if (req->ns) {
  1989. /* if it has a nameserver assigned then this is going */
  1990. /* straight into the inflight queue */
  1991. evdns_request_insert(req, &req_head);
  1992. global_requests_inflight++;
  1993. evdns_request_transmit(req);
  1994. } else {
  1995. evdns_request_insert(req, &req_waiting_head);
  1996. global_requests_waiting++;
  1997. }
  1998. }
  1999. /* exported function */
  2000. int evdns_resolve_ipv4(const char *name, int flags,
  2001. evdns_callback_type callback, void *ptr) {
  2002. log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
  2003. if (flags & DNS_QUERY_NO_SEARCH) {
  2004. struct request *const req =
  2005. request_new(TYPE_A, name, flags, callback, ptr);
  2006. if (req == NULL)
  2007. return (1);
  2008. request_submit(req);
  2009. return (0);
  2010. } else {
  2011. return (search_request_new(TYPE_A, name, flags, callback, ptr));
  2012. }
  2013. }
  2014. /* exported function */
  2015. int evdns_resolve_ipv6(const char *name, int flags,
  2016. evdns_callback_type callback, void *ptr) {
  2017. log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
  2018. if (flags & DNS_QUERY_NO_SEARCH) {
  2019. struct request *const req =
  2020. request_new(TYPE_AAAA, name, flags, callback, ptr);
  2021. if (req == NULL)
  2022. return (1);
  2023. request_submit(req);
  2024. return (0);
  2025. } else {
  2026. return (search_request_new(TYPE_AAAA, name, flags, callback, ptr));
  2027. }
  2028. }
  2029. int evdns_resolve_reverse(struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
  2030. char buf[32];
  2031. struct request *req;
  2032. u32 a;
  2033. assert(in);
  2034. a = ntohl(in->s_addr);
  2035. snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
  2036. (int)(u8)((a )&0xff),
  2037. (int)(u8)((a>>8 )&0xff),
  2038. (int)(u8)((a>>16)&0xff),
  2039. (int)(u8)((a>>24)&0xff));
  2040. log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
  2041. req = request_new(TYPE_PTR, buf, flags, callback, ptr);
  2042. if (!req) return 1;
  2043. request_submit(req);
  2044. return 0;
  2045. }
  2046. int evdns_resolve_reverse_ipv6(struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
  2047. /* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
  2048. char buf[73];
  2049. char *cp;
  2050. struct request *req;
  2051. int i;
  2052. assert(in);
  2053. cp = buf;
  2054. for (i=15; i >= 0; --i) {
  2055. u8 byte = in->s6_addr[i];
  2056. *cp++ = "0123456789abcdef"[byte & 0x0f];
  2057. *cp++ = '.';
  2058. *cp++ = "0123456789abcdef"[byte >> 4];
  2059. *cp++ = '.';
  2060. }
  2061. assert(cp + strlen("ip6.arpa") < buf+sizeof(buf));
  2062. memcpy(cp, "ip6.arpa", strlen("ip6.arpa")+1);
  2063. log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
  2064. req = request_new(TYPE_PTR, buf, flags, callback, ptr);
  2065. if (!req) return 1;
  2066. request_submit(req);
  2067. return 0;
  2068. }
  2069. /*/////////////////////////////////////////////////////////////////// */
  2070. /* Search support */
  2071. /* */
  2072. /* the libc resolver has support for searching a number of domains */
  2073. /* to find a name. If nothing else then it takes the single domain */
  2074. /* from the gethostname() call. */
  2075. /* */
  2076. /* It can also be configured via the domain and search options in a */
  2077. /* resolv.conf. */
  2078. /* */
  2079. /* The ndots option controls how many dots it takes for the resolver */
  2080. /* to decide that a name is non-local and so try a raw lookup first. */
  2081. struct search_domain {
  2082. int len;
  2083. struct search_domain *next;
  2084. /* the text string is appended to this structure */
  2085. };
  2086. struct search_state {
  2087. int refcount;
  2088. int ndots;
  2089. int num_domains;
  2090. struct search_domain *head;
  2091. };
  2092. static struct search_state *global_search_state = NULL;
  2093. static void
  2094. search_state_decref(struct search_state *const state) {
  2095. if (!state) return;
  2096. state->refcount--;
  2097. if (!state->refcount) {
  2098. struct search_domain *next, *dom;
  2099. for (dom = state->head; dom; dom = next) {
  2100. next = dom->next;
  2101. CLEAR(dom);
  2102. _free(dom);
  2103. }
  2104. CLEAR(state);
  2105. _free(state);
  2106. }
  2107. }
  2108. static struct search_state *
  2109. search_state_new(void) {
  2110. struct search_state *state = (struct search_state *) malloc(sizeof(struct search_state));
  2111. if (!state) return NULL;
  2112. memset(state, 0, sizeof(struct search_state));
  2113. state->refcount = 1;
  2114. state->ndots = 1;
  2115. return state;
  2116. }
  2117. static void
  2118. search_postfix_clear(void) {
  2119. search_state_decref(global_search_state);
  2120. global_search_state = search_state_new();
  2121. }
  2122. /* exported function */
  2123. void
  2124. evdns_search_clear(void) {
  2125. search_postfix_clear();
  2126. }
  2127. static void
  2128. search_postfix_add(const char *domain) {
  2129. int domain_len;
  2130. struct search_domain *sdomain;
  2131. while (domain[0] == '.') domain++;
  2132. domain_len = strlen(domain);
  2133. if (!global_search_state) global_search_state = search_state_new();
  2134. if (!global_search_state) return;
  2135. global_search_state->num_domains++;
  2136. sdomain = (struct search_domain *) malloc(sizeof(struct search_domain) + domain_len);
  2137. if (!sdomain) return;
  2138. memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len);
  2139. sdomain->next = global_search_state->head;
  2140. sdomain->len = domain_len;
  2141. global_search_state->head = sdomain;
  2142. }
  2143. /* reverse the order of members in the postfix list. This is needed because, */
  2144. /* when parsing resolv.conf we push elements in the wrong order */
  2145. static void
  2146. search_reverse(void) {
  2147. struct search_domain *cur, *prev = NULL, *next;
  2148. cur = global_search_state->head;
  2149. while (cur) {
  2150. next = cur->next;
  2151. cur->next = prev;
  2152. prev = cur;
  2153. cur = next;
  2154. }
  2155. global_search_state->head = prev;
  2156. }
  2157. /* exported function */
  2158. void
  2159. evdns_search_add(const char *domain) {
  2160. search_postfix_add(domain);
  2161. }
  2162. /* exported function */
  2163. void
  2164. evdns_search_ndots_set(const int ndots) {
  2165. if (!global_search_state) global_search_state = search_state_new();
  2166. if (!global_search_state) return;
  2167. global_search_state->ndots = ndots;
  2168. }
  2169. static void
  2170. search_set_from_hostname(void) {
  2171. char hostname[HOST_NAME_MAX + 1], *domainname;
  2172. search_postfix_clear();
  2173. if (gethostname(hostname, sizeof(hostname))) return;
  2174. domainname = strchr(hostname, '.');
  2175. if (!domainname) return;
  2176. search_postfix_add(domainname);
  2177. }
  2178. /* warning: returns malloced string */
  2179. static char *
  2180. search_make_new(const struct search_state *const state, int n, const char *const base_name) {
  2181. const int base_len = strlen(base_name);
  2182. const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
  2183. struct search_domain *dom;
  2184. for (dom = state->head; dom; dom = dom->next) {
  2185. if (!n--) {
  2186. /* this is the postfix we want */
  2187. /* the actual postfix string is kept at the end of the structure */
  2188. const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
  2189. const int postfix_len = dom->len;
  2190. char *const newname = (char *) malloc(base_len + need_to_append_dot + postfix_len + 1);
  2191. if (!newname) return NULL;
  2192. memcpy(newname, base_name, base_len);
  2193. if (need_to_append_dot) newname[base_len] = '.';
  2194. memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
  2195. newname[base_len + need_to_append_dot + postfix_len] = 0;
  2196. return newname;
  2197. }
  2198. }
  2199. /* we ran off the end of the list and still didn't find the requested string */
  2200. abort();
  2201. return NULL; /* unreachable; stops warnings in some compilers. */
  2202. }
  2203. static int
  2204. search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg) {
  2205. assert(type == TYPE_A || type == TYPE_AAAA);
  2206. if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
  2207. global_search_state &&
  2208. global_search_state->num_domains) {
  2209. /* we have some domains to search */
  2210. struct request *req;
  2211. if (string_num_dots(name) >= global_search_state->ndots) {
  2212. req = request_new(type, name, flags, user_callback, user_arg);
  2213. if (!req) return 1;
  2214. req->search_index = -1;
  2215. } else {
  2216. char *const new_name = search_make_new(global_search_state, 0, name);
  2217. if (!new_name) return 1;
  2218. req = request_new(type, new_name, flags, user_callback, user_arg);
  2219. _free(new_name);
  2220. if (!req) return 1;
  2221. req->search_index = 0;
  2222. }
  2223. req->search_origname = strdup(name);
  2224. req->search_state = global_search_state;
  2225. req->search_flags = flags;
  2226. global_search_state->refcount++;
  2227. request_submit(req);
  2228. return 0;
  2229. } else {
  2230. struct request *const req = request_new(type, name, flags, user_callback, user_arg);
  2231. if (!req) return 1;
  2232. request_submit(req);
  2233. return 0;
  2234. }
  2235. }
  2236. /* this is called when a request has failed to find a name. We need to check */
  2237. /* if it is part of a search and, if so, try the next name in the list */
  2238. /* returns: */
  2239. /* 0 another request has been submitted */
  2240. /* 1 no more requests needed */
  2241. static int
  2242. search_try_next(struct request *const req) {
  2243. if (req->search_state) {
  2244. /* it is part of a search */
  2245. char *new_name;
  2246. struct request *newreq;
  2247. req->search_index++;
  2248. if (req->search_index >= req->search_state->num_domains) {
  2249. /* no more postfixes to try, however we may need to try */
  2250. /* this name without a postfix */
  2251. if (string_num_dots(req->search_origname) < req->search_state->ndots) {
  2252. /* yep, we need to try it raw */
  2253. struct request *const newreq = request_new(req->request_type, req->search_origname, req->search_flags, req->user_callback, req->user_pointer);
  2254. log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", req->search_origname);
  2255. if (newreq) {
  2256. request_submit(newreq);
  2257. return 0;
  2258. }
  2259. }
  2260. return 1;
  2261. }
  2262. new_name = search_make_new(req->search_state, req->search_index, req->search_origname);
  2263. if (!new_name) return 1;
  2264. log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, req->search_index);
  2265. newreq = request_new(req->request_type, new_name, req->search_flags, req->user_callback, req->user_pointer);
  2266. free(new_name);
  2267. if (!newreq) return 1;
  2268. newreq->search_origname = req->search_origname;
  2269. req->search_origname = NULL;
  2270. newreq->search_state = req->search_state;
  2271. newreq->search_flags = req->search_flags;
  2272. newreq->search_index = req->search_index;
  2273. newreq->search_state->refcount++;
  2274. request_submit(newreq);
  2275. return 0;
  2276. }
  2277. return 1;
  2278. }
  2279. static void
  2280. search_request_finished(struct request *const req) {
  2281. if (req->search_state) {
  2282. search_state_decref(req->search_state);
  2283. req->search_state = NULL;
  2284. }
  2285. if (req->search_origname) {
  2286. free(req->search_origname);
  2287. req->search_origname = NULL;
  2288. }
  2289. }
  2290. /*/////////////////////////////////////////////////////////////////// */
  2291. /* Parsing resolv.conf files */
  2292. static void
  2293. evdns_resolv_set_defaults(int flags) {
  2294. /* if the file isn't found then we assume a local resolver */
  2295. if (flags & DNS_OPTION_SEARCH) search_set_from_hostname();
  2296. if (flags & DNS_OPTION_NAMESERVERS) evdns_nameserver_ip_add("127.0.0.1");
  2297. }
  2298. #ifndef HAVE_STRTOK_R
  2299. static char *
  2300. strtok_r(char *s, const char *delim, char **state) {
  2301. (void)state;
  2302. return strtok(s, delim);
  2303. }
  2304. #endif
  2305. /* helper version of atoi which returns -1 on error */
  2306. static int
  2307. strtoint(const char *const str) {
  2308. char *endptr;
  2309. const int r = strtol(str, &endptr, 10);
  2310. if (*endptr) return -1;
  2311. return r;
  2312. }
  2313. /* helper version of atoi that returns -1 on error and clips to bounds. */
  2314. static int
  2315. strtoint_clipped(const char *const str, int min, int max)
  2316. {
  2317. int r = strtoint(str);
  2318. if (r == -1)
  2319. return r;
  2320. else if (r<min)
  2321. return min;
  2322. else if (r>max)
  2323. return max;
  2324. else
  2325. return r;
  2326. }
  2327. /* exported function */
  2328. int
  2329. evdns_set_option(const char *option, const char *val, int flags)
  2330. {
  2331. if (!strncmp(option, "ndots:", 6)) {
  2332. const int ndots = strtoint(val);
  2333. if (ndots == -1) return -1;
  2334. if (!(flags & DNS_OPTION_SEARCH)) return 0;
  2335. log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots);
  2336. if (!global_search_state) global_search_state = search_state_new();
  2337. if (!global_search_state) return -1;
  2338. global_search_state->ndots = ndots;
  2339. } else if (!strncmp(option, "timeout:", 8)) {
  2340. const int timeout = strtoint(val);
  2341. if (timeout == -1) return -1;
  2342. if (!(flags & DNS_OPTION_MISC)) return 0;
  2343. log(EVDNS_LOG_DEBUG, "Setting timeout to %d", timeout);
  2344. global_timeout.tv_sec = timeout;
  2345. } else if (!strncmp(option, "max-timeouts:", 12)) {
  2346. const int maxtimeout = strtoint_clipped(val, 1, 255);
  2347. if (maxtimeout == -1) return -1;
  2348. if (!(flags & DNS_OPTION_MISC)) return 0;
  2349. log(EVDNS_LOG_DEBUG, "Setting maximum allowed timeouts to %d",
  2350. maxtimeout);
  2351. global_max_nameserver_timeout = maxtimeout;
  2352. } else if (!strncmp(option, "max-inflight:", 13)) {
  2353. const int maxinflight = strtoint_clipped(val, 1, 65000);
  2354. if (maxinflight == -1) return -1;
  2355. if (!(flags & DNS_OPTION_MISC)) return 0;
  2356. log(EVDNS_LOG_DEBUG, "Setting maximum inflight requests to %d",
  2357. maxinflight);
  2358. global_max_requests_inflight = maxinflight;
  2359. } else if (!strncmp(option, "attempts:", 9)) {
  2360. int retries = strtoint(val);
  2361. if (retries == -1) return -1;
  2362. if (retries > 255) retries = 255;
  2363. if (!(flags & DNS_OPTION_MISC)) return 0;
  2364. log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries);
  2365. global_max_retransmits = retries;
  2366. }
  2367. return 0;
  2368. }
  2369. static void
  2370. resolv_conf_parse_line(char *const start, int flags) {
  2371. char *strtok_state;
  2372. static const char *const delims = " \t";
  2373. #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
  2374. char *const first_token = strtok_r(start, delims, &strtok_state);
  2375. if (!first_token) return;
  2376. if (!strcmp(first_token, "nameserver") && (flags & DNS_OPTION_NAMESERVERS)) {
  2377. const char *const nameserver = NEXT_TOKEN;
  2378. struct in_addr ina;
  2379. if (inet_aton(nameserver, &ina)) {
  2380. /* address is valid */
  2381. evdns_nameserver_add(ina.s_addr);
  2382. }
  2383. } else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) {
  2384. const char *const domain = NEXT_TOKEN;
  2385. if (domain) {
  2386. search_postfix_clear();
  2387. search_postfix_add(domain);
  2388. }
  2389. } else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) {
  2390. const char *domain;
  2391. search_postfix_clear();
  2392. while ((domain = NEXT_TOKEN)) {
  2393. search_postfix_add(domain);
  2394. }
  2395. search_reverse();
  2396. } else if (!strcmp(first_token, "options")) {
  2397. const char *option;
  2398. while ((option = NEXT_TOKEN)) {
  2399. const char *val = strchr(option, ':');
  2400. evdns_set_option(option, val ? val+1 : "", flags);
  2401. }
  2402. }
  2403. #undef NEXT_TOKEN
  2404. }
  2405. /* exported function */
  2406. /* returns: */
  2407. /* 0 no errors */
  2408. /* 1 failed to open file */
  2409. /* 2 failed to stat file */
  2410. /* 3 file too large */
  2411. /* 4 out of memory */
  2412. /* 5 short read from file */
  2413. int
  2414. evdns_resolv_conf_parse(int flags, const char *const filename) {
  2415. struct stat st;
  2416. int fd, n, r;
  2417. u8 *resolv;
  2418. char *start;
  2419. int err = 0;
  2420. log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename);
  2421. fd = open(filename, O_RDONLY);
  2422. if (fd < 0) {
  2423. evdns_resolv_set_defaults(flags);
  2424. return 1;
  2425. }
  2426. if (fstat(fd, &st)) { err = 2; goto out1; }
  2427. if (!st.st_size) {
  2428. evdns_resolv_set_defaults(flags);
  2429. err = (flags & DNS_OPTION_NAMESERVERS) ? 6 : 0;
  2430. goto out1;
  2431. }
  2432. if (st.st_size > 65535) { err = 3; goto out1; } /* no resolv.conf should be any bigger */
  2433. resolv = (u8 *) malloc((size_t)st.st_size + 1);
  2434. if (!resolv) { err = 4; goto out1; }
  2435. n = 0;
  2436. while ((r = read(fd, resolv+n, (size_t)st.st_size-n)) > 0) {
  2437. n += r;
  2438. if (n == st.st_size)
  2439. break;
  2440. assert(n < st.st_size);
  2441. }
  2442. if (r < 0) { err = 5; goto out2; }
  2443. resolv[n] = 0; /* we malloced an extra byte; this should be fine. */
  2444. start = (char *) resolv;
  2445. for (;;) {
  2446. char *const newline = strchr(start, '\n');
  2447. if (!newline) {
  2448. resolv_conf_parse_line(start, flags);
  2449. break;
  2450. } else {
  2451. *newline = 0;
  2452. resolv_conf_parse_line(start, flags);
  2453. start = newline + 1;
  2454. }
  2455. }
  2456. if (!server_head && (flags & DNS_OPTION_NAMESERVERS)) {
  2457. /* no nameservers were configured. */
  2458. evdns_nameserver_ip_add("127.0.0.1");
  2459. err = 6;
  2460. }
  2461. if (flags & DNS_OPTION_SEARCH && (!global_search_state || global_search_state->num_domains == 0)) {
  2462. search_set_from_hostname();
  2463. }
  2464. out2:
  2465. free(resolv);
  2466. out1:
  2467. close(fd);
  2468. return err;
  2469. }
  2470. #ifdef WIN32
  2471. /* Add multiple nameservers from a space-or-comma-separated list. */
  2472. static int
  2473. evdns_nameserver_ip_add_line(const char *ips) {
  2474. const char *addr;
  2475. char *buf;
  2476. int r;
  2477. while (*ips) {
  2478. while (ISSPACE(*ips) || *ips == ',' || *ips == '\t')
  2479. ++ips;
  2480. addr = ips;
  2481. while (ISDIGIT(*ips) || *ips == '.' || *ips == ':')
  2482. ++ips;
  2483. buf = malloc(ips-addr+1);
  2484. if (!buf) return 4;
  2485. memcpy(buf, addr, ips-addr);
  2486. buf[ips-addr] = '\0';
  2487. r = evdns_nameserver_ip_add(buf);
  2488. free(buf);
  2489. if (r) return r;
  2490. }
  2491. return 0;
  2492. }
  2493. typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*);
  2494. /* Use the windows GetNetworkParams interface in iphlpapi.dll to */
  2495. /* figure out what our nameservers are. */
  2496. static int
  2497. load_nameservers_with_getnetworkparams(void)
  2498. {
  2499. /* Based on MSDN examples and inspection of c-ares code. */
  2500. FIXED_INFO *fixed;
  2501. HMODULE handle = 0;
  2502. ULONG size = sizeof(FIXED_INFO);
  2503. void *buf = NULL;
  2504. int status = 0, r, added_any;
  2505. IP_ADDR_STRING *ns;
  2506. GetNetworkParams_fn_t fn;
  2507. /* XXXX Possibly, we should hardcode the location of this DLL. */
  2508. if (!(handle = LoadLibrary("iphlpapi.dll"))) {
  2509. log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll");
  2510. /* right now status = 0, doesn't that mean "good" - mikec */
  2511. status = -1;
  2512. goto done;
  2513. }
  2514. if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, "GetNetworkParams"))) {
  2515. log(EVDNS_LOG_WARN, "Could not get address of function.");
  2516. /* same as above */
  2517. status = -1;
  2518. goto done;
  2519. }
  2520. buf = malloc(size);
  2521. if (!buf) { status = 4; goto done; }
  2522. fixed = buf;
  2523. r = fn(fixed, &size);
  2524. if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) {
  2525. status = -1;
  2526. goto done;
  2527. }
  2528. if (r != ERROR_SUCCESS) {
  2529. free(buf);
  2530. buf = malloc(size);
  2531. if (!buf) { status = 4; goto done; }
  2532. fixed = buf;
  2533. r = fn(fixed, &size);
  2534. if (r != ERROR_SUCCESS) {
  2535. log(EVDNS_LOG_DEBUG, "fn() failed.");
  2536. status = -1;
  2537. goto done;
  2538. }
  2539. }
  2540. assert(fixed);
  2541. added_any = 0;
  2542. ns = &(fixed->DnsServerList);
  2543. while (ns) {
  2544. r = evdns_nameserver_ip_add_line(ns->IpAddress.String);
  2545. if (r) {
  2546. log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list,error: %d",
  2547. (ns->IpAddress.String),(int)GetLastError());
  2548. status = r;
  2549. goto done;
  2550. } else {
  2551. log(EVDNS_LOG_DEBUG,"Succesfully added %s as nameserver",ns->IpAddress.String);
  2552. }
  2553. added_any++;
  2554. ns = ns->Next;
  2555. }
  2556. if (!added_any) {
  2557. log(EVDNS_LOG_DEBUG, "No nameservers added.");
  2558. status = -1;
  2559. }
  2560. done:
  2561. if (buf)
  2562. free(buf);
  2563. if (handle)
  2564. FreeLibrary(handle);
  2565. return status;
  2566. }
  2567. static int
  2568. config_nameserver_from_reg_key(HKEY key, const char *subkey)
  2569. {
  2570. char *buf;
  2571. DWORD bufsz = 0, type = 0;
  2572. int status = 0;
  2573. if (RegQueryValueEx(key, subkey, 0, &type, NULL, &bufsz)
  2574. != ERROR_MORE_DATA)
  2575. return -1;
  2576. if (!(buf = malloc(bufsz)))
  2577. return -1;
  2578. if (RegQueryValueEx(key, subkey, 0, &type, (LPBYTE)buf, &bufsz)
  2579. == ERROR_SUCCESS && bufsz > 1) {
  2580. status = evdns_nameserver_ip_add_line(buf);
  2581. }
  2582. free(buf);
  2583. return status;
  2584. }
  2585. #define SERVICES_KEY "System\\CurrentControlSet\\Services\\"
  2586. #define WIN_NS_9X_KEY SERVICES_KEY "VxD\\MSTCP"
  2587. #define WIN_NS_NT_KEY SERVICES_KEY "Tcpip\\Parameters"
  2588. static int
  2589. load_nameservers_from_registry(void)
  2590. {
  2591. int found = 0;
  2592. int r;
  2593. #define TRY(k, name) \
  2594. if (!found && config_nameserver_from_reg_key(k,name) == 0) { \
  2595. log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
  2596. found = 1; \
  2597. } else if (!found) { \
  2598. log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
  2599. #k,#name); \
  2600. }
  2601. if (((int)GetVersion()) > 0) { /* NT */
  2602. HKEY nt_key = 0, interfaces_key = 0;
  2603. if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
  2604. KEY_READ, &nt_key) != ERROR_SUCCESS) {
  2605. log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError());
  2606. return -1;
  2607. }
  2608. r = RegOpenKeyEx(nt_key, "Interfaces", 0,
  2609. KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,
  2610. &interfaces_key);
  2611. if (r != ERROR_SUCCESS) {
  2612. log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError());
  2613. return -1;
  2614. }
  2615. TRY(nt_key, "NameServer");
  2616. TRY(nt_key, "DhcpNameServer");
  2617. TRY(interfaces_key, "NameServer");
  2618. TRY(interfaces_key, "DhcpNameServer");
  2619. RegCloseKey(interfaces_key);
  2620. RegCloseKey(nt_key);
  2621. } else {
  2622. HKEY win_key = 0;
  2623. if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0,
  2624. KEY_READ, &win_key) != ERROR_SUCCESS) {
  2625. log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError());
  2626. return -1;
  2627. }
  2628. TRY(win_key, "NameServer");
  2629. RegCloseKey(win_key);
  2630. }
  2631. if (found == 0) {
  2632. log(EVDNS_LOG_WARN,"Didn't find any nameservers.");
  2633. }
  2634. return found ? 0 : -1;
  2635. #undef TRY
  2636. }
  2637. int
  2638. evdns_config_windows_nameservers(void)
  2639. {
  2640. if (load_nameservers_with_getnetworkparams() == 0)
  2641. return 0;
  2642. return load_nameservers_from_registry();
  2643. }
  2644. #endif
  2645. int
  2646. evdns_init(void)
  2647. {
  2648. int res = 0;
  2649. #ifdef WIN32
  2650. evdns_config_windows_nameservers();
  2651. #else
  2652. res = evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
  2653. #endif
  2654. return (res);
  2655. }
  2656. const char *
  2657. evdns_err_to_string(int err)
  2658. {
  2659. switch (err) {
  2660. case DNS_ERR_NONE: return "no error";
  2661. case DNS_ERR_FORMAT: return "misformatted query";
  2662. case DNS_ERR_SERVERFAILED: return "server failed";
  2663. case DNS_ERR_NOTEXIST: return "name does not exist";
  2664. case DNS_ERR_NOTIMPL: return "query not implemented";
  2665. case DNS_ERR_REFUSED: return "refused";
  2666. case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed";
  2667. case DNS_ERR_UNKNOWN: return "unknown";
  2668. case DNS_ERR_TIMEOUT: return "request timed out";
  2669. case DNS_ERR_SHUTDOWN: return "dns subsystem shut down";
  2670. default: return "[Unknown error code]";
  2671. }
  2672. }
  2673. void
  2674. evdns_shutdown(int fail_requests)
  2675. {
  2676. struct nameserver *server, *server_next;
  2677. struct search_domain *dom, *dom_next;
  2678. while (req_head) {
  2679. if (fail_requests)
  2680. reply_callback(req_head, 0, DNS_ERR_SHUTDOWN, NULL);
  2681. request_finished(req_head, &req_head);
  2682. }
  2683. while (req_waiting_head) {
  2684. if (fail_requests)
  2685. reply_callback(req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL);
  2686. request_finished(req_waiting_head, &req_waiting_head);
  2687. }
  2688. global_requests_inflight = global_requests_waiting = 0;
  2689. for (server = server_head; server; server = server_next) {
  2690. server_next = server->next;
  2691. if (server->socket >= 0)
  2692. CLOSE_SOCKET(server->socket);
  2693. (void) event_del(&server->event);
  2694. if (server->state == 0)
  2695. (void) event_del(&server->timeout_event);
  2696. CLEAR(server);
  2697. free(server);
  2698. if (server_next == server_head)
  2699. break;
  2700. }
  2701. server_head = NULL;
  2702. global_good_nameservers = 0;
  2703. if (global_search_state) {
  2704. for (dom = global_search_state->head; dom; dom = dom_next) {
  2705. dom_next = dom->next;
  2706. CLEAR(dom);
  2707. free(dom);
  2708. }
  2709. CLEAR(global_search_state);
  2710. free(global_search_state);
  2711. global_search_state = NULL;
  2712. }
  2713. evdns_log_fn = NULL;
  2714. }
  2715. #ifdef EVDNS_MAIN
  2716. void
  2717. main_callback(int result, char type, int count, int ttl,
  2718. void *addrs, void *orig) {
  2719. char *n = (char*)orig;
  2720. int i;
  2721. for (i = 0; i < count; ++i) {
  2722. if (type == DNS_IPv4_A) {
  2723. printf("%s: %s\n", n, debug_ntoa(((u32*)addrs)[i]));
  2724. } else if (type == DNS_PTR) {
  2725. printf("%s: %s\n", n, ((char**)addrs)[i]);
  2726. }
  2727. }
  2728. if (!count) {
  2729. printf("%s: No answer (%d)\n", n, result);
  2730. }
  2731. fflush(stdout);
  2732. }
  2733. void
  2734. evdns_server_callback(struct evdns_server_request *req, void *data)
  2735. {
  2736. int i, r;
  2737. (void)data;
  2738. /* dummy; give 192.168.11.11 as an answer for all A questions,
  2739. * give foo.bar.example.com as an answer for all PTR questions. */
  2740. for (i = 0; i < req->nquestions; ++i) {
  2741. u32 ans = htonl(0xc0a80b0bUL);
  2742. if (req->questions[i]->type == EVDNS_TYPE_A &&
  2743. req->questions[i]->class == EVDNS_CLASS_INET) {
  2744. printf(" -- replying for %s (A)\n", req->questions[i]->name);
  2745. r = evdns_server_request_add_a_reply(req, req->questions[i]->name,
  2746. 1, &ans, 10);
  2747. if (r<0)
  2748. printf("eeep, didn't work.\n");
  2749. } else if (req->questions[i]->type == EVDNS_TYPE_PTR &&
  2750. req->questions[i]->class == EVDNS_CLASS_INET) {
  2751. printf(" -- replying for %s (PTR)\n", req->questions[i]->name);
  2752. r = evdns_server_request_add_ptr_reply(req, NULL, req->questions[i]->name,
  2753. "foo.bar.example.com", 10);
  2754. } else {
  2755. printf(" -- skipping %s [%d %d]\n", req->questions[i]->name,
  2756. req->questions[i]->type, req->questions[i]->class);
  2757. }
  2758. }
  2759. r = evdns_request_respond(req, 0);
  2760. if (r<0)
  2761. printf("eeek, couldn't send reply.\n");
  2762. }
  2763. void
  2764. logfn(int is_warn, const char *msg) {
  2765. (void) is_warn;
  2766. fprintf(stderr, "%s\n", msg);
  2767. }
  2768. int
  2769. main(int c, char **v) {
  2770. int idx;
  2771. int reverse = 0, verbose = 1, servertest = 0;
  2772. if (c<2) {
  2773. fprintf(stderr, "syntax: %s [-x] [-v] hostname\n", v[0]);
  2774. fprintf(stderr, "syntax: %s [-servertest]\n", v[0]);
  2775. return 1;
  2776. }
  2777. idx = 1;
  2778. while (idx < c && v[idx][0] == '-') {
  2779. if (!strcmp(v[idx], "-x"))
  2780. reverse = 1;
  2781. else if (!strcmp(v[idx], "-v"))
  2782. verbose = 1;
  2783. else if (!strcmp(v[idx], "-servertest"))
  2784. servertest = 1;
  2785. else
  2786. fprintf(stderr, "Unknown option %s\n", v[idx]);
  2787. ++idx;
  2788. }
  2789. event_init();
  2790. if (verbose)
  2791. evdns_set_log_fn(logfn);
  2792. evdns_resolv_conf_parse(DNS_OPTION_NAMESERVERS, "/etc/resolv.conf");
  2793. if (servertest) {
  2794. int sock;
  2795. struct sockaddr_in my_addr;
  2796. sock = socket(PF_INET, SOCK_DGRAM, 0);
  2797. fcntl(sock, F_SETFL, O_NONBLOCK);
  2798. my_addr.sin_family = AF_INET;
  2799. my_addr.sin_port = htons(10053);
  2800. my_addr.sin_addr.s_addr = INADDR_ANY;
  2801. if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr))<0) {
  2802. perror("bind");
  2803. exit(1);
  2804. }
  2805. evdns_add_server_port(sock, 0, evdns_server_callback, NULL);
  2806. }
  2807. for (; idx < c; ++idx) {
  2808. if (reverse) {
  2809. struct in_addr addr;
  2810. if (!inet_aton(v[idx], &addr)) {
  2811. fprintf(stderr, "Skipping non-IP %s\n", v[idx]);
  2812. continue;
  2813. }
  2814. fprintf(stderr, "resolving %s...\n",v[idx]);
  2815. evdns_resolve_reverse(&addr, 0, main_callback, v[idx]);
  2816. } else {
  2817. fprintf(stderr, "resolving (fwd) %s...\n",v[idx]);
  2818. evdns_resolve_ipv4(v[idx], 0, main_callback, v[idx]);
  2819. }
  2820. }
  2821. fflush(stdout);
  2822. event_dispatch();
  2823. return 0;
  2824. }
  2825. #endif
  2826. /* Local Variables: */
  2827. /* tab-width: 4 */
  2828. /* c-basic-offset: 4 */
  2829. /* indent-tabs-mode: t */
  2830. /* End: */