eventdns.c 89 KB

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