eventdns.c 87 KB

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