eventdns.c 92 KB

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