eventdns.c 90 KB

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