eventdns.c 83 KB

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