eventdns.c 82 KB

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