eventdns.c 84 KB

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