eventdns.c 92 KB

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