eventdns.c 84 KB

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