eventdns.c 92 KB

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