eventdns.c 84 KB

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