eventdns.c 93 KB

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